I have got further into my program and am at the last hurdle, i am using String.split to split InetAddress IP using getInetAddress. so IP is storing the host name and ip address which is split by a /. I am trying to split the string using string.split but when i then try system.out or writing to a file it seems to lose the part of the string before the /. here is the code.

public void writefile(InetAddress IP) {
        String [] Name;
        String IPaddress = IP.toString();

        Name = IPaddress.split("/");


        System.out.println("The IP addres is: " + Name[1]);
        System.out.println("The Hostname is: " + Name[0]);
        try {

            File f = new File(file);
            FileWriter fw = new FileWriter(f);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("The Hostname is: " + Name + "\n");
            bw.flush();
            bw.write("The IP address is: " + IPaddress + "\n");
            bw.flush();
        } catch (IOException e) {
            System.err.println("File not found/created");
        }
    }

It is pringint the IP address fine but losing the host name, why?

This part works just fine here for me using InetAddress.getLocalHost() as a test address

System.out.println("The IP addres is: " + Name[1]);
        System.out.println("The Hostname is: " + Name[0]);

I'm not after a localhost but a remote one so have to use getinetaddress

That's not really the point. It was just an address to test with.

The split works just fine in your println() statements. Your file writing code is another story because you are writing totally different things there. I'm not sure why you're trying to write the "Name" array as your host name, but that obviously won't work.

after some further testing getinetaddress isn't getting the hostname, just the IP, so what can i use to get the hostname of the remote client?

If it's not being returned as part of the InetAddress then I don't know that you can. That's a question of your local set up and name resolution.

As far as the splitting though, you don't really need to split the toString() representation of the address. You can use the methods to get them directly

System.out.println("host: "+IP.getHostName());
            System.out.println("ip: "+IP.getHostAddress());
Member Avatar for ztini
Name = IPaddress.split("/");
 
            bw.write("The Hostname is: " + Name + "\n");
            bw.write("The IP address is: " + IPaddress + "\n");

You need to point an index in the array:

Name = IPaddress.split("/");
 
            bw.write("The Hostname is: " + [B]Name[0][/B] + "\n");
            bw.write("The IP address is: " + [B]Name[1][/B] + "\n");
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.