socktest.java

来自「JGRoups源码」· Java 代码 · 共 77 行

JAVA
77
字号
package org.jgroups.tests;import org.jgroups.util.Util;import java.net.*;import java.io.IOException;import java.util.Enumeration;/** * Created by IntelliJ IDEA. * User: bela * Date: May 16, 2006 * Time: 9:02:06 AM * To change this template use File | Settings | File Templates. */public class socktest {    public static void main(String[] args) throws Exception {        ServerSocket s;	System.out.println("trying to determine first IPv6 address");        InetAddress bind_addr=getFirstNonLoopbackIPv6Address();        // InetAddress bind_addr=getByName("eth0");        s=new ServerSocket(7500, 50, bind_addr);        System.out.println("socket: " + s + ", local address is " + s.getLocalSocketAddress());        while(true) {            Socket client_sock=s.accept();            System.out.println("accepted connection from " + client_sock);            Util.sleep(5000);        }    }    public static InetAddress getByName(String interfaceName) throws Exception {        NetworkInterface intf=NetworkInterface.getByName(interfaceName);        if(intf == null) return null;        for(Enumeration en=intf.getInetAddresses(); en.hasMoreElements();) {            InetAddress addr=(InetAddress)en.nextElement();            return addr;        }        return null;    }    public static InetAddress getFirstNonLoopbackIPv6Address() throws SocketException {        System.out.println("fetching the network interfaces");        Enumeration en=NetworkInterface.getNetworkInterfaces();        boolean preferIpv4=false;        boolean preferIPv6=true;        while(en.hasMoreElements()) {            NetworkInterface i=(NetworkInterface)en.nextElement();            System.out.println("-- looking at: " + i);            for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) {                InetAddress addr=(InetAddress)en2.nextElement();                System.out.println("-- addr: " + addr);                if(!addr.isLoopbackAddress()) {                    if(addr instanceof Inet4Address) {                        if(preferIPv6)                            continue;                        return addr;                    }                    if(addr instanceof Inet6Address) {                        if(preferIpv4)                            continue;                        return addr;                    }                }            }        }        return null;    }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?