简体   繁体   中英

JDK 1.7 DatagramSocket not binding IP and port correctly

I am writing a server program using UDP in Java. I am using, of course, DatagramSocket for the server UDP socket. I am on Mac OS X 10.9.1, and my coding environment is set to JDK 1.7.

My problem is that when I initialize my socket like this:

serverSocket = new DatagramSocket(19132);

It doesn't throw an exception, but when I try to log it to the console, like this:

log("Starting Minecraft PE server on " + serverSocket.getInetAddress() + ":" + serverSocket.getPort());

The .getInetAddress is null, and the port is -1. The port that I am trying to bind to is 19132. My firewall was turned off while I was trying the code, it still was null. Here is some output fromt the log:

2014-01-18 17:16:20 [MCPE_Server][INFO] Starting Minecraft PE server on null:-1

You're calling the methods that return the other side of the 'connection'. Datagram sockets are never really connected like a TCP connection but 'connecting' it fixes the destination of the datagrams. It's optional.

You are looking for the address to which the socket is bound; for that you need the methods getLocalPort and getLocalAddress . getLocalAddress is still not going to return an IP number though; if you create the DatagramSocket through the constructor that takes only a port number, it will listen on all interfaces which is indicated by the 'address' 0.0.0.0.

If you run this bit of code:

DatagramSocket serverSocket = new DatagramSocket(19132);
System.out.println("Starting Minecraft PE server on " + serverSocket.getLocalAddress() + ":" + serverSocket.getLocalPort());

You'll get output like this:

Starting Minecraft PE server on 0.0.0.0/0.0.0.0:19132

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