简体   繁体   中英

I can't assign more than one Address in java ServerSocket

Thanks for helping me. I am trying to run more than one server in my java program with this code:

addr = InetAddress.getByName("127.0.0."+MyIP);
ss = new ServerSocket(port,100,addr);

but the code works for just MyIP=1,is there a way to solve this?

If you are asking if a system can have multiple 127.xxx addresses, then the answer is "It depends on your OS, and network configuration".

On my Linux / Fedora 20 box, "/etc/sysconfig/network-scripts/ifcfg-lo" defines all of 127.0.0.0/8 as loopback addresses. However, if you look at the file, the implication is that the "lo" device could be configured to allow fewer addresses (or if you are crazy) other addresses as loopback IP addresses.

On Mac OSX, 127.0.0.1 is the only loopback address configured by default, but it is easy to configure more (see references).

From what I have read, on Windows 7 there is only one loopback address - 127.0.0.1. It is hard-wired, and treated specially by the networking stack. Windows does have a "Loopback Adapter" but its purpose is different.

TL;DR - Your code would work on Linux, but not on Windows. On Mac OS/X you need to tweak the network configs to make it work.

References:


If you are asking if you can bind multiple IP addresses to a single ServerSocket , then the answer is "No".

A ServerSocket can be bound to at most one IP address.

If you want to listen / accept using multiple IP addresses, then you need to use multiple ServerSocket instances.

However, the IP address 0.0.0.0 is called the "local wildcard" address. If you bind to this, you are effectively binding to the IP addresses of all network interfaces (including loopback interfaces)

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM