Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

i have a little promblem. When i connect to my UDP server using localhost as a hostname, everything goes fine, but when i use my ip as a hostname, the client cant connect to the server. What could couse such issue? As i know the server and the client are fine, because i had the same problem with other servers. But if i'm not right, i give you the code... Server:

import java.io.*;
import java.net.*;
import java.util.*;

public class UDPServer extends Thread {
    public final static int PORT = 7331;
    private final static int BUFFER = 1024;

    private DatagramSocket socket;
    private ArrayList<InetAddress> clientAddresses;
    private ArrayList<Integer> clientPorts;
    private HashSet<String> existingClients;
    public UDPServer() throws IOException {
        socket = new DatagramSocket(PORT);
        clientAddresses = new ArrayList();
        clientPorts = new ArrayList();
        existingClients = new HashSet();
    }

    public void run() {
        byte[] buf = new byte[BUFFER];
        while (true) {
            try {
                Arrays.fill(buf, (byte)0);
                DatagramPacket packet = new DatagramPacket(buf, buf.length);
                socket.receive(packet);

                String content = new String(buf, buf.length);

                InetAddress clientAddress = packet.getAddress();
                int clientPort = packet.getPort();

                String id = clientAddress.toString() + "," + clientPort;
                if (!existingClients.contains(id)) {
                    existingClients.add( id );
                    clientPorts.add( clientPort );
                    clientAddresses.add(clientAddress);
                }

                System.out.println(id + " : " + content);
                byte[] data = (id + " : " +  content).getBytes();
                for (int i=0; i < clientAddresses.size(); i++) {
                    InetAddress cl = clientAddresses.get(i);
                    int cp = clientPorts.get(i);
                    packet = new DatagramPacket(data, data.length, cl, cp);
                    socket.send(packet);
                }
            } catch(Exception e) {
                System.err.println(e);
            }
        }
    }

    public static void main(String args[]) throws Exception {
        UDPServer s = new UDPServer();
        s.start();
    }
}

Client:

import java.io.*;
import java.net.*;
import java.util.*;


class MessageSender implements Runnable {
    public final static int PORT = 7331;
    private DatagramSocket sock;
    private String hostname;
    MessageSender(DatagramSocket s, String h) {
        sock = s;
        hostname = h;
    }
    private void sendMessage(String s) throws Exception {
        byte buf[] = s.getBytes();
        InetAddress address = InetAddress.getByName(hostname);
        DatagramPacket packet = new DatagramPacket(buf, buf.length, address, PORT);
        sock.send(packet);
    }
    public void run() {
        boolean connected = false;
        do {
            try {
                sendMessage("GREETINGS");
                connected = true;
            } catch (Exception e) {

            }
        } while (!connected);
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            try {
                while (!in.ready()) {
                    Thread.sleep(100);
                }
                sendMessage(in.readLine());
            } catch(Exception e) {
                System.err.println(e);
            }
        }
    }
}
class MessageReceiver implements Runnable {
    DatagramSocket sock;
    byte buf[];
    MessageReceiver(DatagramSocket s) {
        sock = s;
        buf = new byte[1024];
    }
    public void run() {
        while (true) {
            try {
                DatagramPacket packet = new DatagramPacket(buf, buf.length);
                sock.receive(packet);
                String received = new String(packet.getData(), 0, packet.getLength());
                System.out.println(received);
            } catch(Exception e) {
                System.err.println(e);
            }
        }
    }
}
public class UDPClient {

    public static void main(String args[]) throws Exception {
        String host = null;
        if (args.length < 1) {
            System.out.println("Usage: java ChatClient <server_hostname>");
            System.exit(0);
        } else {
            host = args[0];
        }
        DatagramSocket socket = new DatagramSocket();
        MessageReceiver r = new MessageReceiver(socket);
        MessageSender s = new MessageSender(socket, host);
        Thread rt = new Thread(r);
        Thread st = new Thread(s);
        rt.start(); st.start();
    }
}
share|improve this question
    
By "my ip", do you mean the same ip at it shows here: whatismyip.org ? –  William 'MindWorX' Mariager Feb 11 '12 at 14:01
    
Yes. I think there something wrong with my computer or something... –  Liukas Feb 11 '12 at 14:07
    
Can you ping yourself with that IP? –  Maik Semder Feb 11 '12 at 14:38
    
Do you use a router? What does your ipconfig/ifconfig say? –  Maik Semder Feb 11 '12 at 14:41
    
Are the client and server both running on your local PC? Are you able to connect when you use "127.0.0.1" instead of your network interface IP address? I seem to recall a bug in the UdpSocket class that sounds like this. –  phord Mar 30 '12 at 21:55
add comment

2 Answers

up vote 0 down vote accepted

As the above commenters were mentioning, you are probably in a subnet behind a router using a NAT configuration. This gives your network one single external IP. You need to figure out and use your local IP in the network. Use ipconfig/ifconfig (depends on your OS) to figure this out. For Windows, open a command prompt. (Click start then run and enter "cmd") And then enter "ipconfig", you can then find your IPv4 address under the relevant device/connection.

Ok, so going to elaborate a little more. In this case your phone is the router. If it's configured to use NAT, it can only have one external IP for all the devices in it's subnet. You can connect to the "outside" but they can't explicitly connect to you. In order to remedy this you're going to have to adjust your phone settings or connect using an alternative.

For a better and more specific explanation check out this page I grabbed from the top of a google search.

share|improve this answer
    
Can explain more? I'm using android phone as a portable wi-fi hotspot. –  Liukas Feb 11 '12 at 16:47
    
OS - Windows 7 :) –  Liukas Feb 11 '12 at 16:47
    
I just checked, and saw that ip on my pc and phone is the same. I think that is cousing problems with the server conection. Do you know how can i get a diferent ip on my pc? –  Liukas Feb 11 '12 at 17:33
    
Did you check with ipconfig? If they have the same IP then I'm pretty sure you shouldn't even be able to connect to the internet. But here is how to adjust network settings. windows.microsoft.com/en-US/windows7/Change-TCP-IP-settings –  KlashnikovKid Feb 11 '12 at 17:40
    
What exact setting do i have to change? –  Liukas Feb 11 '12 at 17:52
show 7 more comments

The problem is with how you created the DatagramSocket. as stated in DatagramSocket refrence you are using DatagramSocket(int port) which only bind server on local loopback device. To grant access to other computers to connect your server you need to use either DatagramSocket(int port, InetAddress laddr) or DatagramSocket(SocketAddress bindaddr). in these cases you can specify an IP address. to let users to connect from any computer connected to your device use '0.0.0.0' as an IP address as stated here.

share|improve this answer
    
Actually, the reference you linked to says: "Constructs a datagram socket and binds it to the specified port on the local host machine. The socket will be bound to the wildcard address, an IP address chosen by the kernel." So that means it's binding to the given port on the wildcard address, not just on the loopback device. –  justinian Feb 12 '12 at 18:21
    
@justinian seems you are right. I didn't read the the information completely. But I had same issue with Sockets (in C++) longs ago. his problem seemed to be the firewall on his system. anyway I'll keep this answer since it may help others. –  Ali.S Feb 12 '12 at 19:47
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.