读取计算机的拨号上网临时的IP地址和局域网分配的固定IP地址: 在程序设计中,我们是通过一个自定义的函数--getIPAddress ( )来读取IP地址的。首先看一下如何读取本地固定的IP地址的。在Dns类中还定义了一个方法GetHostByName( )。此方法的返回值时IPHostEntry 对象,此对象有一个属性是AddressList,此属性是一个IPAddress类型的数组,包含了计算机此时的所有的IP地址信息。这当中也就包含了拨号上网得到的临时分配的IP地址和局域网固定的IP地址。具体实现语句如下: private static stringgetIPAddress ( ) { System.Net.IPAddress addr; // 获得本机局域网IP地址 addr = new System.Net.IPAddress ( Dns.GetHostByName (Dns.GetHostName ( ) ) .AddressList [0].Address ) ; return addr.ToString ( ) ; } 源程序如下: using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Net;namespace GetIP { public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.ComponentModel.Container components = null; public Form1() { InitializeComponent(); label1.Text=System.Net.Dns.GetHostName(); label2.Text=getIpAddress(); } protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.SuspendLayout(); this.label1.Location = new System.Drawing.Point(48, 24); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(264, 24); this.label1.TabIndex = 0; this.label1.Text = "label1"; this.label2.Location = new System.Drawing.Point(48, 64); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(264, 24); this.label2.TabIndex = 1; this.label2.Text = "label2"; this.AutoScaleBaseSize = new System.Drawing.Size(6, 14); this.ClientSize = new System.Drawing.Size(376, 221); this.Controls.AddRange(new System.Windows.Forms.Control[] {this.label2,this.label1}); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); } #endregion static void Main() { Application.Run(new Form1()); } private static string getIpAddress() { System.Net.IPAddress addr; addr=new System.Net.IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address) ; return addr.ToString(); } } }
using System.Net.SocketsIPHostEntry m_local = Dns.Resolve(Dns.GetHostName()); Console.WriteLine(m_local.AddressList[0].ToString());
首先,添加命名空间: using System.Net; 如下方法得到本机IP:System.Net.IPAddress addr = new System.Net.IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address);
// This program shows how to use the IPAddress class to obtain a server // IP addressess and related information.using System; using System.Net; using System.Net.Sockets; using System.Text.RegularExpressions;namespace Mssc.Services.ConnectionManagement { class TestIPAddress { /** * The IPAddresses method obtains the selected server IP address information. * It then displays the type of address family supported by the server and its * IP address in standard and byte format. **/ private static void IPAddresses(string server) { try { System.Text.ASCIIEncoding ASCII = new System.Text.ASCIIEncoding();
// Get server related information. IPHostEntry heserver = Dns.Resolve(server); // Loop on the AddressList foreach (IPAddress curAdd in heserver.AddressList) { // Display the type of address family supported by the server. If the // server is IPv6-enabled this value is: InternNetworkV6. If the server // is also IPv4-enabled there will be an additional value of InterNetwork. Console.WriteLine("AddressFamily: " + curAdd.AddressFamily.ToString());
// Display the ScopeId property in case of IPV6 addresses. if(curAdd.AddressFamily.ToString() == ProtocolFamily.InterNetworkV6.ToString()) Console.WriteLine("Scope Id: " + curAdd.ScopeId.ToString()); // Display the server IP address in the standard format. In // IPv4 the format will be dotted-quad notation, in IPv6 it will be // in in colon-hexadecimal notation. Console.WriteLine("Address: " + curAdd.ToString());
// Display the server IP address in byte format. Console.Write("AddressBytes: "); Byte[] bytes = curAdd.GetAddressBytes(); for (int i = 0; i < bytes.Length; i++) { Console.Write(bytes[i]); } Console.WriteLine("\r\n"); } } catch (Exception e) { Console.WriteLine("[DoResolve] Exception: " + e.ToString()); } } // This IPAddressAdditionalInfo displays additional server address information. private static void IPAddressAdditionalInfo() { try { // Display the flags that show if the server supports IPv4 or IPv6 // address schemas. Console.WriteLine("\r\nSupportsIPv4: " + Socket.SupportsIPv4); Console.WriteLine("SupportsIPv6: " + Socket.SupportsIPv6); if (Socket.SupportsIPv6) { // Display the server Any address. This IP address indicates that the server // should listen for client activity on all network interfaces. Console.WriteLine("\r\nIPv6Any: " + IPAddress.IPv6Any.ToString()); // Display the server loopback address. Console.WriteLine("IPv6Loopback: " + IPAddress.IPv6Loopback.ToString());
// Used during autoconfiguration first phase. Console.WriteLine("IPv6None: " + IPAddress.IPv6None.ToString());
// Define a regular expression to parse user's input. // This is a security check. It allows only // alphanumeric input string between 2 to 40 character long. Regex rex = new Regex(@"^[a-zA-Z]\w{1,39}$"); if (args.Length < 1) { // If no server name is passed as an argument to this program, use the current // server name as default. server = Dns.GetHostName(); Console.WriteLine("Using current host: " + server); } else { server = args[0]; if (!(rex.Match(server)).Success) { Console.WriteLine("Input string format not allowed."); return; } } // Get the list of the addresses associated with the requested server. IPAddresses(server);
// Get additonal address information. IPAddressAdditionalInfo(); } } }
在程序设计中,我们是通过一个自定义的函数--getIPAddress ( )来读取IP地址的。首先看一下如何读取本地固定的IP地址的。在Dns类中还定义了一个方法GetHostByName( )。此方法的返回值时IPHostEntry 对象,此对象有一个属性是AddressList,此属性是一个IPAddress类型的数组,包含了计算机此时的所有的IP地址信息。这当中也就包含了拨号上网得到的临时分配的IP地址和局域网固定的IP地址。具体实现语句如下:
private static stringgetIPAddress ( )
{
System.Net.IPAddress addr;
// 获得本机局域网IP地址
addr = new System.Net.IPAddress ( Dns.GetHostByName (Dns.GetHostName ( ) ) .AddressList [0].Address ) ;
return addr.ToString ( ) ;
}
源程序如下:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;namespace GetIP
{
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.ComponentModel.Container components = null;
public Form1()
{
InitializeComponent();
label1.Text=System.Net.Dns.GetHostName();
label2.Text=getIpAddress();
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.SuspendLayout(); this.label1.Location = new System.Drawing.Point(48, 24);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(264, 24);
this.label1.TabIndex = 0;
this.label1.Text = "label1"; this.label2.Location = new System.Drawing.Point(48, 64);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(264, 24);
this.label2.TabIndex = 1;
this.label2.Text = "label2"; this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(376, 221);
this.Controls.AddRange(new System.Windows.Forms.Control[] {this.label2,this.label1});
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
static void Main()
{
Application.Run(new Form1());
}
private static string getIpAddress()
{
System.Net.IPAddress addr;
addr=new System.Net.IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address) ;
return addr.ToString();
}
}
}
Console.WriteLine(m_local.AddressList[0].ToString());
{
string ClientIP=CStr(Request.ServerVariables["HTTP_X_FORWARDED_FOR"]); if(ClientIP==null || ClientIP=="")
ClientIP=CStr(Request.ServerVariables["REMOTE_ADDR"]);
return ClientIP;
}
HttpContext.Current.Request.UserHostAddress.ToString().Trim()
// This program shows how to use the IPAddress class to obtain a server
// IP addressess and related information.using System;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;namespace Mssc.Services.ConnectionManagement
{ class TestIPAddress
{ /**
* The IPAddresses method obtains the selected server IP address information.
* It then displays the type of address family supported by the server and its
* IP address in standard and byte format.
**/
private static void IPAddresses(string server)
{
try
{
System.Text.ASCIIEncoding ASCII = new System.Text.ASCIIEncoding();
// Get server related information.
IPHostEntry heserver = Dns.Resolve(server); // Loop on the AddressList
foreach (IPAddress curAdd in heserver.AddressList)
{
// Display the type of address family supported by the server. If the
// server is IPv6-enabled this value is: InternNetworkV6. If the server
// is also IPv4-enabled there will be an additional value of InterNetwork.
Console.WriteLine("AddressFamily: " + curAdd.AddressFamily.ToString());
// Display the ScopeId property in case of IPV6 addresses.
if(curAdd.AddressFamily.ToString() == ProtocolFamily.InterNetworkV6.ToString())
Console.WriteLine("Scope Id: " + curAdd.ScopeId.ToString());
// Display the server IP address in the standard format. In
// IPv4 the format will be dotted-quad notation, in IPv6 it will be
// in in colon-hexadecimal notation.
Console.WriteLine("Address: " + curAdd.ToString());
// Display the server IP address in byte format.
Console.Write("AddressBytes: "); Byte[] bytes = curAdd.GetAddressBytes();
for (int i = 0; i < bytes.Length; i++)
{
Console.Write(bytes[i]);
} Console.WriteLine("\r\n"); } }
catch (Exception e)
{
Console.WriteLine("[DoResolve] Exception: " + e.ToString());
}
} // This IPAddressAdditionalInfo displays additional server address information.
private static void IPAddressAdditionalInfo()
{
try
{
// Display the flags that show if the server supports IPv4 or IPv6
// address schemas.
Console.WriteLine("\r\nSupportsIPv4: " + Socket.SupportsIPv4);
Console.WriteLine("SupportsIPv6: " + Socket.SupportsIPv6); if (Socket.SupportsIPv6)
{
// Display the server Any address. This IP address indicates that the server
// should listen for client activity on all network interfaces.
Console.WriteLine("\r\nIPv6Any: " + IPAddress.IPv6Any.ToString()); // Display the server loopback address.
Console.WriteLine("IPv6Loopback: " + IPAddress.IPv6Loopback.ToString());
// Used during autoconfiguration first phase.
Console.WriteLine("IPv6None: " + IPAddress.IPv6None.ToString());
Console.WriteLine("IsLoopback(IPv6Loopback): " + IPAddress.IsLoopback(IPAddress.IPv6Loopback));
}
Console.WriteLine("IsLoopback(Loopback): " + IPAddress.IsLoopback(IPAddress.Loopback));
}
catch (Exception e)
{
Console.WriteLine("[IPAddresses] Exception: " + e.ToString());
}
}
public static void Main(string[] args)
{
string server = null;
// Define a regular expression to parse user's input.
// This is a security check. It allows only
// alphanumeric input string between 2 to 40 character long.
Regex rex = new Regex(@"^[a-zA-Z]\w{1,39}$"); if (args.Length < 1)
{
// If no server name is passed as an argument to this program, use the current
// server name as default.
server = Dns.GetHostName();
Console.WriteLine("Using current host: " + server);
}
else
{
server = args[0];
if (!(rex.Match(server)).Success)
{
Console.WriteLine("Input string format not allowed.");
return;
}
} // Get the list of the addresses associated with the requested server.
IPAddresses(server);
// Get additonal address information.
IPAddressAdditionalInfo();
} }
}
[DllImport("Iphlpapi.dll")]
private static unsafe extern int SendARP(Int32 dest,Int32 host,ref IntPtr mac,ref IntPtr length);
[DllImport("Ws2_32.dll")]
private static extern Int32 inet_addr(string ip);Int32 ldest= inet_addr("157.60.68.163");//目的地的ip
Int32 lhost= inet_addr("157.60.68.33");//本地的iptry
{
Byte[] macinfo=new Byte[6];
Int32 length=6;
IntPtr mac=new IntPtr(macinfo[0]);
IntPtr len=new IntPtr(6);
int ii=SendARP(ldest,lhost, ref mac, ref len);
Console.WriteLine("Mac Add:"+mac);
Console.WriteLine("length:"+len);
}
catch(Exception err)
{
Console.WriteLine(err);
}
addr=new System.Net.IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address) ;
addr转成string类型就是ip地址了