Figure 1: Output Screen show find "youtube.com" ip address.
Figure 2: Output Screen find "Lan" ip address.
Figure 3: Output screen with invalid input.
This is example the way we can find Remote ip address.
Class Definition:
System.Net
- Dns class
- GetHostAddresses method
Syntax:
public static IPAddress[] GetHostAddresses (
string hostNameOrAddress
)
Parameters : hostNameOrAddress
Type: System.String
The host name or IP address to resolve.
Return Value:
Type: System.Net.IPAddress[]
An array of type IPAddress that holds the IP addresses for the host that is specified by the
hostNameOrAddress parameter.
The IPAddress class contains the address of a computer on an IP network.
//Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
namespace gethostip
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1FindClick(object sender, EventArgs e)
{
string hostname = "";
hostname = textBoxInput.Text;
try
{
IPAddress[] ipaddr = System.Net.Dns.GetHostAddresses(hostname);
for (int i = 0; i < ipaddr.Length; i++)
{
textBoxOutput.Text += "" + ipaddr[i].ToString() + Environment.NewLine;
}
}
catch (System.Net.Sockets.SocketException )
{
textBoxOutput.Text = "No such host is known";
}
}
private void button2ClearClick(object sender, EventArgs e)
{
textBoxOutput.Text = "";
}
}
}
Remark : To protect some Error when you run this program in case you enter invalid format of hostname and/or IP Address format. so you should have ...try {
...
}
catch (System.Net.Sockets.SocketException) {
... your error message here ...
}
If you have "run" this program without ...try exception... and input invalid hostname such as " 5a.5a 999" the debuger will report you with error message..."System.Net.Sockets.SocketException : no such host known". where become to me known what we do catch for...? System.Net.Sockets.SocketException
No comments:
Post a Comment