hello, i want to show the client's ip and machine name in ListView. Please help, Thank you.

i also created code the collection for the listview collection

class ClientCollection
    {
        
        public string userIpadd { get; set; }
        public string userPcname { get; set; }

        public ClientCollection()
        {
        }
    }

the code below will only show the number that the client connected to the server.

// Update the list of clients that is displayed
		void UpdateClientList()
		{
                listView1.Items.Clear();
		for(int i = 0; i < m_workerSocketList.Count; i++)
		{
		string clientKey = Convert.ToString(i+1);
		Socket workerSocket = (Socket)m_workerSocketList[i];

                ListViewItem item = new ListViewItem();

		if(workerSocket != null)
		{
		if(workerSocket.Connected)
		{
                   listView1.Items.Add(clientKey);
		}
		}
		}
		}

For computer name: Dns.GetHostEntry(stringIP).HostName should work. For the ip, I've used this before:

string sIP = (mySocket.RemoteEndPoint.ToString().Split(':'))[0];
IPAddress tempIP = IPAddress.Parse(sIP);

This will seperate the port number from the IP in the RemoteEndPoint, then will parse this as an IP address. Though there might be a better way to do this...

Or something like this:

IPAddress[] addresses = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress address in addresses) {
    //for IPv4 .. if needed :)
    if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) {
        Console.WriteLine(address);
    }
}

Or something like this:

IPAddress[] addresses = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress address in addresses) {
    //for IPv4 .. if needed :)
    if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) {
        Console.WriteLine(address);
    }
}

This will only get the IP's of the local computer. Correct me if I'm wrong, but if you are trying to evaluate the IP of a connected socket this would not be of much use. Also note, this will be the internal IP of the current computer - if you are behind a router this will not be the external IP (which is what a server really needs to talk to you). For this reason, the IP MUST be extracted from the socket, or an external IP resolution must be performed prior to sending the data, and this IP must be included in the serialized data sent (via whatsmyip.com or something similar).

commented: Thanks for correcting :) +7

Agreed, my bad. Thanks for correcting :)

thank you very much for the help. i've been trying out, here is the code

void UpdateClientList()
		{
            listView1.Items.Clear();
            IPHostEntry he = Dns.GetHostEntry(clientinfo);
            
            string clientIPAddress = Dns.GetHostAddresses(clientinfo).ToString();
			for(int i = 0; i < m_workerSocketList.Count; i++)
			{
			string clientKey = Convert.ToString(i+1);
			Socket workerSocket = (Socket)m_workerSocketList[i];
                        ListViewItem result = new ListViewItem();

                        result.SubItems.Add(he.HostName);
                        result.SubItems.Add(clientIPAddress);

				if(workerSocket != null)
				{
					if(workerSocket.Connected)
					{
                        
                        listView1.Items.Add(clientKey);
                        listView1.Items.Add(result);
					}
				}
			}
		}

but the result came differently, few problems.

Because i run both client server program in one machine, so i confuse, based on the code, the HostName will show the connected client's PC name? and will not retrieve the name from local machine if i run the client in different PC?

Another problem, is the IP address code turn out like the attachment image. Also, the list view number and connected pc name shows in different line.

Please help me.

At first, Dns.GetHostAddresses means a few adresses (see MSDN). It returns an array.

The second is .. as MSDN says:

Dns.GetHostName Method
Gets the host name of the local computer.

Means that it will get the address of the machine, on which, this part of code was executed.
If you'd have a client part of your application on a different PC and run this code in the clients part - then it would return the address of that remote PC. But if you would run this code on a server, you'd always get the same result - name of a current machine.

At first, Dns.GetHostAddresses means a few adresses (see MSDN). It returns an array.

The second is .. as MSDN says:

Means that it will get the address of the machine, on which, this part of code was executed.
If you'd have a client part of your application on a different PC and run this code in the clients part - then it would return the address of that remote PC. But if you would run this code on a server, you'd always get the same result - name of a current machine.

thanks for reply. i try the client program in different computer, turn out retrieve back the server pc name, not the client pc name. :( then how to retrieve the connected client pc name?? i made some changes in the code (below), but still get the same result. what code should be typed?

i remove this code string clientIPAddress = Dns.GetHostAddresses(clientinfo).ToString(); and add this result.SubItems.Add(he.AddressList.ToString()); thanks again.

UPDATE:

i made more changes, i try run client program in different computer but result still shows the local machine host name and ip address, not client's pc name and it ip address. :(

what should i do? please help. thank in advance

here is the code i changed

void UpdateClientList()
	{
            IPHostEntry he = Dns.GetHostEntry(clientinfo);
            listView1.Items.Clear();

	    for(int i = 0; i < m_workerSocketList.Count; i++)
	    {
		string clientKey = Convert.ToString(i+1);
		Socket workerSocket = (Socket)m_workerSocketList[i];
                ListViewItem result = new ListViewItem();

                result.SubItems.Add(he.HostName);
                
                foreach (IPAddress ipadd in he.AddressList)
                {
                    if (ipadd.AddressFamily == AddressFamily.InterNetwork)
                    {
                        result.SubItems.Add(ipadd.ToString());
                    }
                }
               if(workerSocket != null)
	      {
		   if(workerSocket.Connected)
		   {
                        listView1.Items.Add(clientKey);
                        listView1.Items.Add(result);
		}
	 }
    }
}

For computer name: Dns.GetHostEntry(stringIP).HostName should work. For the ip, I've used this before:

string sIP = (mySocket.RemoteEndPoint.ToString().Split(':'))[0];
IPAddress tempIP = IPAddress.Parse(sIP);

This will seperate the port number from the IP in the RemoteEndPoint, then will parse this as an IP address. Though there might be a better way to do this...

UPDATE again:

hello skatamatic, i try out the code you gave, but still didnt show the client' pc name :( don't know what did i wrong, but thankfully it show the client's ip address, thanks :)

for the ip address code, have error when the client disconnected. string sIP = (workerSocket.RemoteEndPoint.ToString().Split(':'))[0]; it said NullReferenceException was unhandled by user code "Object reference not set to an instance of an object."

how to fix it? what should i change?

here is the code i modified again:

void UpdateClientList()
	{
            listView1.Items.Clear();
            
	    for(int i = 0; i < m_workerSocketList.Count; i++)
		{
	         string clientKey = Convert.ToString(i+1);
		 Socket workerSocket = (Socket)m_workerSocketList[i];

                 ListViewItem result = new ListViewItem();
                 string clientinfo = Dns.GetHostName();
                 IPHostEntry he = Dns.GetHostEntry(clientinfo);

                 string sIP = (workerSocket.RemoteEndPoint.ToString().Split(':'))[0];
                 IPAddress tempIP = IPAddress.Parse(sIP);

		 if(workerSocket != null)
		 {
			if(workerSocket.Connected)
			{
                        result.SubItems.Add(he.HostName);
                        result.SubItems.Add(tempIP.ToString());

                        listView1.Items.Add(clientKey);
                        listView1.Items.Add(result);
			}
		  }
	}
}

thanks again.

Maybe try sending the host name to the server in a connection packet (could contain other info too), so that the server doesn't have to resolve it.

To fix that error, you can either use a try/catch block or just check if the socket is null.

Maybe try sending the host name to the server in a connection packet (could contain other info too), so that the server doesn't have to resolve it.

To fix that error, you can either use a try/catch block or just check if the socket is null.

thanks again. Yup, the error fixed.
for the client name, do you mean code like this:

System.Net.IPHostEntry host = new System.Net.IPHostEntry();
host = System.Net.Dns.GetHostEntry(Request.ServerVariables["REMOTE_HOST"]).HostName;

been search on internet, said the code above can retrieve client pc name, but why i type in the code, the 'Request' show error? please help.

anyone please help, i tried out many codes, but still unable to retrieve the connected client's machine name and kept getting the local machine name even though i run in different computer.

thanks in advance.

problem finally solved :), anyway, thank you for all your help, skatamatic and Antenka.

Hi, haanjae.
Maybe you could post the solution you came out with, so the people, who would face same problem also be able to obtain the solution ;)

you are right :)
here is the solution:
just add one line to display the client's machine name, the rest code is the same.

if(workerSocket.Connected)
{
    IPHostEntry he = Dns.GetHostEntry(tempIP); //display client machine name, retrieve the name from IP address
     result.Text = clientKey.ToString();
      result.SubItems.Add(he.HostName);
       result.SubItems.Add(tempIP.ToString());
         listView1.Items.Add(result);
}
commented: Good job! :) +7
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.