简体   繁体   中英

How to send udp packets using Ip address from source to destination host?

Source side:

import java.io.*;

import java.net.*; 

class Server
{ 

 public static void main(String args[]) throws Exception 
   {

    DatagramSocket ds = new DatagramSocket(50074); 
    byte[] ms = new byte[1024]; 
    String a="Computer";
    ms=a.getBytes();
    DatagramPacket ps = new DatagramPacket(ms, ms.length, InetAddress.getByName("Destination Ip address"),1599); 
    ds.send(ps);

   }


}

Destination side:

import java.io.*; 

import java.net.*; 

class Client
{ 

 public static void main(String args[]) throws Exception 
   {

   DatagramSocket ds = new DatagramSocket(1599);

   byte[] ms = new byte[10024];

   DatagramPacket ps = new DatagramPacket(ms,ms.length);

   ds.receive(ps);

   System.out.println(new String(ps.getData()));

}

}

This is my program, but it is not working. When I am giving Destination IP adress="localhost" it is working well. But if I replacing localhost as "Destination ip address like 117.201.12.80 " it is not working.. please help me to solve this problem

localhost or 127.0.0.1 is the system default IP address, if you have notice that server like tomcat, xmapp, IIS, etc all uses these IP address for running of there applications.

So the program given by you will run only if you specify 127.0.0.1 or localhost , if you get connected to internet or create an wifi network for playing games which having IP address like 117.201.12.80 than you can run your program with that IP-address.

Sorry - didn't see the response

You're calling InetAddress.getByName() when you should be calling InetAddress.getByAddress(byte[] addr) with each segment of addr filled with 117 201 12 80 respectively

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