Skip to content

Instantly share code, notes, and snippets.

@rbochet
Created May 11, 2011 15:42
Show Gist options
  • Save rbochet/966707 to your computer and use it in GitHub Desktop.
Save rbochet/966707 to your computer and use it in GitHub Desktop.
This program runs a server that give you the IP address of every client that tries to connect. It works on both side (display the IP and send it back). It is quite useful as a whatismyip service on a local network.
package fr.stackr.java.gimmeyourip;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.WriteAbortedException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
* This program runs a server that give you the IP address of every client that
* try to connect. It works on both side (display the IP and send it back). Its
* quite useful as a whatismyip service on a local network.
*
* @author Romain Bochet
*/
public class Main {
/**
* Translation of IP in ascii
*/
private final static int PORT_NUMBER = 7380;
/**
* Endless while waiting for new connections.
*
* @param args
* Not used
* @throws IOException
* If the socket initialisation fails
*/
public static void main(String[] args) throws IOException {
System.out.println("GimmeMyIP started (host: "
+ InetAddress.getLocalHost() + ") -- listen on port "
+ Main.PORT_NUMBER);
System.out.println("Command: telnet "
+ InetAddress.getLocalHost().getHostAddress() + " "
+ Main.PORT_NUMBER);
ServerSocket srv = new ServerSocket(Main.PORT_NUMBER);
while (true) {
Socket socket = srv.accept();
System.out.println("Client connected: " + socket.getInetAddress());
OutputStreamWriter output = new OutputStreamWriter(
socket.getOutputStream());
output.write(socket.getInetAddress().getHostAddress());
output.write('\n');
output.flush();
socket.close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment