C语言获取本机IP地址
C#获取本机IP地址(ipv4)
C#获取本机IP地址(ipv4)获取本机所有IP地址:这些地址是包含所有⽹卡(虚拟⽹卡)的ipv4和ipv6地址。
string name = Dns.GetHostName();IPAddress[] ipadrlist = Dns.GetHostAddresses(name);获取本机所有IPV4地址:string name = Dns.GetHostName();IPAddress[] ipadrlist = Dns.GetHostAddresses(name);foreach (IPAddress ipa in ipadrlist){if (ipa.AddressFamily == AddressFamily.InterNetwork)Console.Writeline(ipa.ToString());}若要单单获取ipv4地址,可以⽤IPAdress.AddressFamily 属性判断:对于 IPv4,返回 InterNetwork;对于 IPv6,返回InterNetworkV6。
然⽽如果本机可能有多个ipv4的地址,那如何获取访问默认⽹关时使⽤的⽹卡IP呢。
在CSDN论坛找到了⼤神的⽅法,⽤的是查询本机路由表。
获取本机正在使⽤的ipv4地址(访问互联⽹的IP)可别⼩看,还是有很多需要考虑的:1.⼀个电脑有多个⽹卡,有线的、⽆线的、还有vmare虚拟的两个⽹卡。
2.就算只有⼀个⽹卡,但是该⽹卡配置了N个IP地址.其中还包括ipv6地址。
/// <summary>/// 获取当前使⽤的IP/// </summary>/// <returns></returns>public static string GetLocalIP(){string result = RunApp("route", "print",true);Match m = Regex.Match(result, @"0.0.0.0\s+0.0.0.0\s+(\d+.\d+.\d+.\d+)\s+(\d+.\d+.\d+.\d+)");if (m.Success){return m.Groups[2].Value;}else{try{.Sockets.TcpClient c = new .Sockets.TcpClient();c.Connect("", 80);string ip = ((.IPEndPoint)c.Client.LocalEndPoint).Address.ToString();c.Close();return ip;}catch (Exception){return null;}}}/// <summary>/// 获取本机主DNS/// </summary>/// <returns></returns>public static string GetPrimaryDNS(){string result = RunApp("nslookup", "",true);Match m = Regex.Match(result, @"\d+\.\d+\.\d+\.\d+");if (m.Success){return m.Value;}else{return null;}}/// <summary>/// 运⾏⼀个控制台程序并返回其输出参数。
C# .net获取电脑IP和MAC
C# .net获取电脑IP和MAC/// <summary>/// 取得用户客户端IP(穿过代理服务器取远程用户真实IP地址)/// </summary>public static string GetClientIP(){//如果使用代理,获取真实IPstring userip = string.Empty;if(HttpContext.Current.Request.ServerVariables["HTTP_X_FORW ARDED_FOR"] != ""){userip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];}else{userip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];}if (userip == null || userip == ""){userip = erHostAddress;}return userip;//HttpRequest Request = HttpContext.Current.Request;//try//{// if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)// {// return HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();// }// else// {// return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();// }//}//catch { return "127.0.0.1"; }}//获取mac地址public static string GetCustomerMac(){string IP = GetClientIP();string dirResults = "";ProcessStartInfo psi = new ProcessStartInfo();Process proc = new Process();psi.FileName = "nbtstat";psi.RedirectStandardInput = false;psi.RedirectStandardOutput = true;psi.Arguments = "-a " + IP;eShellExecute = false;proc = Process.Start(psi);dirResults = proc.StandardOutput.ReadToEnd();proc.WaitForExit();//匹配mac地址Match m = Regex.Match(dirResults, "\\w+\\-\\w+\\-\\w+\\-\\w+\\-\\w+\\-\\w\\w");//若匹配成功则返回mac,否则返回找不到主机信息if (m.ToString() != ""){return m.ToString();}else{return "找不到主机信息";}}。
cc++实现获取域名的IP地址
cc++实现获取域名的IP地址c/c++实现获取域名的IP地址// GetHostIP.cpp : 定义控制台应⽤程序的⼊⼝点。
//#include "stdafx.h"#include <winsock2.h>#include <ws2tcpip.h>#include <stdio.h>#include <windows.h>#pragma comment(lib, "ws2_32.lib")int main(int argc, char **argv){//-----------------------------------------// Declare and initialize variables/** WSADATA结构被⽤来储存调⽤AfxSocketInit全局函数返回的Windows Sockets初始化信息。
* 这个结构被⽤来存储被WSAStartup函数调⽤后返回的Windows Sockets数据。
它包含Winsock.dll执⾏的数据。
*/WSADATA wsaData;int iResult;DWORD dwError; /*每个word为2个字节的长度,DWORD 双字即为4个字节,每个字节是8位*/int i = 0;struct hostent *remoteHost; /*域名*/char *host_name; /*主机名*/struct in_addr addr; /*ip*/char **pAlias;// Validate the parametersif (argc != 2) {printf("usage: GetHostIP hostname\n");return 1;}// 此处应添加的程序如下// 1. 当初始化winsocketiResult = WSAStartup(MAKEWORD(2,2),&wsaData);/* & 取地址*/// 2. 检查该socket是否初始化成功,即该socket是否等于0;如果初始化不成功,应当给出错误报警,并结束程序。
C#编程获取IP地址的方法示例
C#编程获取IP地址的⽅法⽰例本⽂实例讲述了C#编程获取IP地址的⽅法。
分享给⼤家供⼤家参考,具体如下:1、获取客户端IP/// <summary>/// 获取客户端Ip/// </summary>/// <returns></returns>public String GetClientIp(){String clientIP = "";if (System.Web.HttpContext.Current != null){clientIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];if (string.IsNullOrEmpty(clientIP) || (clientIP.ToLower() == "unknown")){clientIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_REAL_IP"];if (string.IsNullOrEmpty(clientIP)){clientIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];}}else{clientIP = clientIP.Split(',')[0];}}return clientIP;}2、服务器端获取客户端请求IP和客户端机器名称/// <summary>/// 服务器端获取客户端请求IP和客户端机器名称/// </summary>public static void GetClientInfo(){OperationContext context = OperationContext.Current;MessageProperties messageProperties = context.IncomingMessageProperties;RemoteEndpointMessageProperty endpointProperty = messageProperties[] as RemoteEndpointMessageProperty; HttpRequestMessageProperty requestProperty = messageProperties[] as HttpRequestMessageProperty;string clientIp = !string.IsNullOrEmpty(requestProperty.Headers["X-Real-IP"]) ? requestProperty.Headers["X-Real-IP"] : endpointProperty.Address;string clientName = Environment.MachineName;Console.WriteLine("ClientIp: " + clientIp + "clientName:" + clientName);}PS:这⾥再为⼤家推荐⼏款IP相关⼯具供⼤家参考使⽤:更多关于C#相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》、《》、《》及《》希望本⽂所述对⼤家C#程序设计有所帮助。
C#获取本地IP的四种方式示例详解
C#获取本地IP的四种⽅式⽰例详解1.第⼀种⽅式采⽤.Dns的GetHostAddress的⽅式,具体请看代码:/// <summary>/// ⽹络不通畅可以获取/// 不过能获取到具体的IP/// </summary>/// <returns></returns>public static List<IPAddress> GetByGetHostAddresses(){try{IPAddress[] adds = Dns.GetHostAddresses(Dns.GetHostName());return adds == null || adds.Length == 0 ? new List<IPAddress>() : adds.ToList<IPAddress>();}catch (Exception){return new List<IPAddress>();}}这种⽅式受到⽹络的影响,如果没有连接到⽹络,本地配置的部分IP是获取不到的,我也遇到⼀种情况是,电脑环境正常,就是获取不到,原因⾄今还不知道;2.第⼆种⽅式采⽤System.Management.ManagementClass来获取,详细请看代码:/// <summary>/// 只有⽹络通畅才能获取/// </summary>/// <returns></returns>public static List<IPAddress> GetByManagementClass(){try{ManagementClass mClass = new System.Management.ManagementClass("Win32_NetworkAdapterConfiguration");ManagementObjectCollection managementObjectCollection = mClass.GetInstances();List<IPAddress> ls = new List<IPAddress>();foreach (var item in managementObjectCollection){if ((bool)item["IPEnabled"] == true){foreach (var ip in (string[])item["IPAddress"]){IPAddress ipout = null;IPAddress.TryParse(ip, out ipout);if (ipout != null){ls.Add(ipout);}}}}return ls;}catch (Exception){return new List<IPAddress>();}}同样的这种⽅式也受到⽹络的约束,没有联⽹的状态下不⼀定能够获取到IP;3.第三种⽅式我们平时在命令⾏中输⼊ipconfig命令同样也是能获取,在程序中启动Ipconfig应⽤程序,然后解析出来,也是可以获取得到IP,详细请看代码:public static List<IPAddress> GetByCMD(){try{Process cmd = new Process();cmd.StartInfo.FileName = "ipconfig.exe";cmd.StartInfo.Arguments = "/all";cmd.StartInfo.RedirectStandardOutput = true;cmd.StartInfo.RedirectStandardInput = true;eShellExecute = false;cmd.StartInfo.CreateNoWindow = true;cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;cmd.Start();string info = "";List<IPAddress> ls = new List<IPAddress>();// info = cmd.StandardOutput.ReadToEnd();Regex validipregex = new Regex(@"\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}");//new Regex(@"^(([1-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([1-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");while ((info = cmd.StandardOutput.ReadLine()) != null){IPAddress ip = null;Console.WriteLine(info);info = validipregex.Match(info).Value;IPAddress.TryParse(info, out ip);if (ip != null){ls.Add(ip);}}cmd.WaitForExit();cmd.Close();return ls;}catch (Exception){return new List<IPAddress>();}}即便是通过这种⽅式来获取IP,如果在本机电脑没有联⽹的状态下,也是获取不到IP的,并且也不太建议使⽤这种⽅式;4.第四种⽅法采⽤NetworkInterface.GetAllNetworkInterfaces的⽅式是不受⽹络的影响的,联⽹或者不联⽹都能够获取到IP,详细请看代码:/// <summary>/// ⽆论⽹络通不通都能获取到Ip/// </summary>/// <returns></returns>public static List<IPAddress> GetByNetworkInterface(){try{NetworkInterface[] intf = NetworkInterface.GetAllNetworkInterfaces();List<IPAddress> ls = new List<IPAddress>();foreach (var item in intf){IPInterfaceProperties adapterPropertis = item.GetIPProperties();UnicastIPAddressInformationCollection coll = adapterPropertis.UnicastAddresses;foreach (var col in coll){ls.Add(col.Address);}}return ls;}catch (Exception){return new List<IPAddress>();}}以上所说的联⽹,包括连接在局域⽹中。
用MFC如何获取本地主机名和IP地址
1.在文件StdAfx.h文件里面加入#include <afxsock.h>
2.在MFC工程文件name+APP.cpp里面对socket初始化
for( i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )
{
char str[100];
char addr[20];
int j;
LPCSTR psz=inet_ntoa (*(struct in_addr *)pHost->h_addr_list[i]);
if (!AfxSocketInit())
{
return FALSE;
}
并且
在BOOL CDsfsdApp::InitInstance()文件里面重启socket服务器在return FALSE前加上
WSADATA wsaData;
WSAStartup(MAKEWORD(1,1),&wsaData);
再添加一个ExitInstance方法
如
int CDsfsdApp::ExitInstance()
{
WSACleanup();
return CWinApp::ExitInstance();
}
3.在窗体的单击事件下,写下面代码
void CDsfsdDlg::OnQuery()
{
char szHostName[128];
C#获取本机IP的6种方法
C#获取本机IP的6种方法print?1、//GetHostNameprivate void GetIP(){string hostName = Dns.GetHostName();//本机名//.IPAddress[] addressList = Dns.GetHostByName(hostName).AddressList;//会警告GetHostByName()已过期,我运行时且只返回了一个IPv4的地址.IPAddress[] addressList = Dns.GetHostAddresses(hostName);//会返回所有地址,包括IPv4和IPv6foreach (IPAddress ip in addressList){listBox1.Items.Add(ip.ToString());}}1、//GetHostNameprivate void GetIP(){string hostName = Dns.GetHostName();//本机名//.IPAddress[] addressList = Dns.GetHostByName(hostName).AddressList;//会警告GetHostByName()已过期,我运行时且只返回了一个IPv4的地址.IPAddress[] addressList = Dns.GetHostAddresses(hostName);//会返回所有地址,包括IPv4和IPv6foreach (IPAddress ip in addressList){listBox1.Items.Add(ip.ToString());}}2、使用IPHostEntry获取本机局域网地址[csharp]static string GetLocalIp(){string hostname = Dns.GetHostName();//得到本机名//IPHostEntry localhost = Dns.GetHostByName(hostname);//方法已过期,只得到IPv4的地址IPHostEntry localhost = Dns.GetHostEntry(hostname);IPAddress localaddr = localhost.AddressList[0];return localaddr.ToString();}static string GetLocalIp(){string hostname = Dns.GetHostName();//得到本机名//IPHostEntry localhost = Dns.GetHostByName(hostname);//方法已过期,只得到IPv4的地址IPHostEntry localhost = Dns.GetHostEntry(hostname);IPAddress localaddr = localhost.AddressList[0];return localaddr.ToString();}3、获取本机网络ip地址[csharp]string strUrl = "提供IP查询的网站的链接";Uri uri = new Uri(strUrl);WebRequest webreq = WebRequest.Create(uri);Stream s = webreq .GetResponse().GetResponseStream();StreamReader sr = new StreamReader(s, Encoding.Default);string all = sr.ReadToEnd();int i = all.IndexOf("[") + 1;//分析字符串得到IPreturn ip;/*我用的是/getip.php?action=getip&ip_url=&from=web(这种链接很容易找的,百度“IP”得到一些网站,分析一下网站的链接就能得到)返回的数据是:<div class="well"><p>当前IP:<code>0.0.0.0</code> 来自:XX省XX市电信</p><p>GeoIP: Beijing, China</p></div>解析这段就行*/string strUrl = "提供IP查询的网站的链接";Uri uri = new Uri(strUrl);WebRequest webreq = WebRequest.Create(uri);Stream s = webreq .GetResponse().GetResponseStream();StreamReader sr = new StreamReader(s, Encoding.Default);string all = sr.ReadToEnd();int i = all.IndexOf("[") + 1;//分析字符串得到IPreturn ip;/*我用的是/getip.php?action=getip&ip_url=&from=web(这种链接很容易找的,百度“IP”得到一些网站,分析一下网站的链接就能得到)返回的数据是:<div class="well"><p>当前IP:<code>0.0.0.0</code> 来自:XX省XX市电信</p><p>GeoIP: Beijing, China</p></div>解析这段就行*/4、//由于用到了ManagementClass、ManagementObjectCollection;必须添加引用System.Management.dll及using System.Management;[csharp] view plaincopyprint?private void GetIP2(){string stringMAC = "";string stringIP = "";ManagementClass managementClass = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection managementObjectCollection = managementClass.GetInstances(); foreach(ManagementObject managementObject in managementObjectCollection){if ((bool)managementObject["IPEnabled"] == true){stringMAC += managementObject["MACAddress"].ToString();string[] IPAddresses = (string[])managementObject["IPAddress"];if (IPAddresses.Length > 0){stringIP = IPAddresses[0];}}}txtMAC.Text = stringMAC.ToString();txtIP.Text = stringIP.ToString();}private void GetIP2(){string stringMAC = "";string stringIP = "";ManagementClass managementClass = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection managementObjectCollection = managementClass.GetInstances(); foreach(ManagementObject managementObject in managementObjectCollection){if ((bool)managementObject["IPEnabled"] == true){stringMAC += managementObject["MACAddress"].ToString();string[] IPAddresses = (string[])managementObject["IPAddress"];if (IPAddresses.Length > 0){stringIP = IPAddresses[0];}}}txtMAC.Text = stringMAC.ToString();txtIP.Text = stringIP.ToString();}5、通过获取CMD里ipconfig命令的结果来得到IP[csharp]private void GetIP6(){Process cmd = new Process();cmd.StartInfo.FileName = "ipconfig.exe";//设置程序名cmd.StartInfo.Arguments = "/all"; //参数//重定向标准输出cmd.StartInfo.RedirectStandardOutput = true;cmd.StartInfo.RedirectStandardInput = true;eShellExecute = false;cmd.StartInfo.CreateNoWindow = true;//不显示窗口(控制台程序是黑屏)//cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;//暂时不明白什么意思/*收集一下有备无患关于:ProcessWindowStyle.Hidden隐藏后如何再显示?hwndWin32Host = Win32Native.FindWindow(null, win32Exinfo.windowsName);Win32Native.ShowWindow(hwndWin32Host, 1); //先FindWindow找到窗口后再ShowWindow */cmd.Start();string info = cmd.StandardOutput.ReadToEnd();cmd.WaitForExit();cmd.Close();textBox1.AppendText(info);}private void GetIP6(){Process cmd = new Process();cmd.StartInfo.FileName = "ipconfig.exe";//设置程序名cmd.StartInfo.Arguments = "/all"; //参数//重定向标准输出cmd.StartInfo.RedirectStandardOutput = true;cmd.StartInfo.RedirectStandardInput = true;eShellExecute = false;cmd.StartInfo.CreateNoWindow = true;//不显示窗口(控制台程序是黑屏)//cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;//暂时不明白什么意思/*收集一下有备无患关于:ProcessWindowStyle.Hidden隐藏后如何再显示?hwndWin32Host = Win32Native.FindWindow(null, win32Exinfo.windowsName);Win32Native.ShowWindow(hwndWin32Host, 1); //先FindWindow找到窗口后再ShowWindow */cmd.Start();string info = cmd.StandardOutput.ReadToEnd();cmd.WaitForExit();cmd.Close();textBox1.AppendText(info);}6、NetworkInformation[csharp]private void GetIP5(){//需要的命名空间//using workInformation;//using .Sockets;string str = "";NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); int i = 0;foreach (NetworkInterface adapter in adapters){IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); UnicastIPAddressInformationCollection allAddress = adapterProperties.UnicastAddresses;if (allAddress.Count > 0){str += "interface " + i + "description:\n\t " + adapter.Description + "\n ";i++;foreach (UnicastIPAddressInformation addr in allAddress){if (addr.Address.AddressFamily == AddressFamily.InterNetworkV6){ipListComb.Items.Add(addr.Address);}if (addr.Address.AddressFamily == AddressFamily.InterNetwork){comboBox1.Items.Add(addr.Address);}}}}MessageBox.Show(str);}private void GetIP5(){//需要的命名空间//using workInformation;//using .Sockets;string str = "";NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); int i = 0;foreach (NetworkInterface adapter in adapters){IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); UnicastIPAddressInformationCollection allAddress = adapterProperties.UnicastAddresses;if (allAddress.Count > 0){str += "interface " + i + "description:\n\t " + adapter.Description + "\n ";i++;foreach (UnicastIPAddressInformation addr in allAddress){if (addr.Address.AddressFamily == AddressFamily.InterNetworkV6){ipListComb.Items.Add(addr.Address);}if (addr.Address.AddressFamily == AddressFamily.InterNetwork){comboBox1.Items.Add(addr.Address);}}}}MessageBox.Show(str);}。
C语言获取IP和MAC码
首先看从C语音的几种方法比较起,看看如下,结果是获取IP和MAC码C#遍历局域网的几种方法及比较扫描局域网IP列表的几种方法很多软件都有获知局域网在线计算机IP的功能,但是在.net怎么实现呢,有好多方法,下面我给大家介绍几种,供大家参考。
1、微软社区上介绍了使用Active Directory 来遍历局域网利用DirectoryEntry组件来查看网络网址:/china/communITy/program/originalarticles/techdoc/DirectoryEntry.mspx private void EnumComputers(){using(DirectoryEntry root = new DirectoryEntry("WinNT:")){foreach(DirectoryEntry domain in root.Children){Console.WriteLine("Domain | WorkGroup: "+);foreach(DirectoryEntry computer in domain.Children){Console.WriteLine("Computer: "+);}}}}效果评价:速度慢,效率低,还有一个无效结果 Computer: Schema 使用的过程中注意虑掉。
2、利用Dns.GetHostByAddress和IPHostEntry遍历局域网private void EnumComputers(){for (int i = 1; i <= 255; i++){string scanIP = "192.168.0." + i.ToString();IPAddress myScanIP = IPAddress.Parse(scanIP);IPHostEntry myScanHost = null;trymyScanHost = Dns.GetHostByAddress(myScanIP);}catch{continue;}if (myScanHost != null){Console.WriteLine(scanIP+"|"+myScanHost.HostName);}}}效果评价:效率低,速度慢,不是一般的慢。
C#获取计算机名跟IP地址
bel1 = new bel ( ) ;
bel2 = new bel ( ) ;
//先继承一个Label 类
label1.Location = new System.Drawing.Point ( 24 , 16 ) ;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D ;
// 设定窗体的边界类型
this.ForeColor = System.Drawing.SystemColors.Desktop ;
this.Font = new System.Drawing.Font ( "宋体" , 10 , System.Drawing.FontStyle.Bold ) ;
//先继承一个Label 类
label1.Location = new System.Drawing.Point ( 24 , 16 ) ;
label2.Location = new System.Drawing.Point ( 44 , 36 ) ;
//设定 Label的显示位置
label1.Text = "主机名称:" .Dns.GetHostName ( ) ;
this.Controls.Add ( bel1 ) ;
this.Controls.Add ( bel2 ) ;
}
private static string getIPAddress ( )
{
.IPAddress addr;
// 获得本机局域网IP地址
在前面已经说了,GetHostByName ( )方法的返回值时IPHostEntry 对象,此对象的属性 AddressList,是一个IPAddress类型的数组,包含了计算机此时的所有的IP地址信息。在ip01.cs中AddressList [0].Address是固定的IP地址,而对于上网动态分配的IP地址是.AddressList [1].Address。据此我们可以的得到读取拨号上网动态分配的IP地址的源程序:
如何通过C获取IP地址及默认网关
示例程序:usi ng Sy stem.Net;usin g Sys tem;usin g Sys tem.M anage ment;usi ng Sy stem.Runti me.In terop Servi ces;pub lic c lassgetIP{ [Dl lImpo rt("I phlpa pi.dl l")]pr ivate stat ic ex ternint S endAR P(Int32 de st,In t32 h ost,r ef In t64 m ac,re f Int32 le ngth); [DllI mport("Ws2_32.d ll")]p rivat e sta tic e xtern Int32 ine t_add r(str ing i p); //获取本机的IP publ ic st ringgetLo calIP() { str ing s trHos tName = Dn s.Get HostN ame(); //得到本机的主机名IP HostE ntryipEnt ry =Dns.G etHos tByNa me(st rHost Name); //取得本机IPstrin g str Addr= ipE ntry.Addre ssLis t[0].ToStr ing(); retu rn(st rAddr); } //获取本机的MA Cpubli c str ing g etLoc alMac() { str ing m ac =null;Manag ement Objec tSear cherquery =new Mana gemen tObje ctSea rcher("SEL ECT * FROM Win32_Net workA dapte rConf igura tion") ; Ma nagem entOb jectC ollec tionquery Colle ction = qu ery.G et();forea ch( M anage mentO bject mo i n que ryCol lecti on ){ if(mo["IPEna bled"].ToS tring() == "Tru e") ma c = m o["Ma cAddr ess"].ToSt ring(); } re turn(mac);}//获取远程主机IPp ublic stri ng[]getRe moteI P(str ing R emote HostN ame){I PHost Entry ipEn try = Dns.GetHo stByN ame(R emote HostN ame);IPAdd ress[] IpA ddr = ipEn try.A ddres sList; stri ng[]strAd dr =new s tring[IpAd dr.Le ngth]; for(inti=0;i {strAd dr[i] = Ip Addr[i].To Strin g();}retur n(str Addr);}//获取远程主机MA Cpubli c str ing g etRem oteMa c(str ing l ocalI P, st ringremot eIP){I nt32ldest= ine t_add r(rem oteIP); //目的ipI nt32lhost= ine t_add r(loc alIP); //本地ip try{ Int64 ma cinfo = ne w Int64(); Int32 len = 6; intres = Send ARP(l dest,0, re f mac info, reflen); retu rn Co nvert.ToSt ring(macin fo,16); } ca tch(E xcept ion e rr) {Conso le.Wr iteLi ne("E rror:{0}",err.M essag e); }r eturn 0.To Strin g();} publ ic st aticvoidMain(strin g[] a rgs){g etIPgi =new g etIP(); Con sole.Write Line("本地网卡信息:"); Cons ole.W riteL ine(g i.get Local IP()+ " - " +gi.ge tLoca lMac()); Con sole.Write Line("\n\r远程网卡信息:"); st ring[] tem p = g i.get Remot eIP("scmob ile-t j2");for(i nt i=0;i { Co nsole.Writ eLine(temp[i]);} Cons ole.W riteL ine(g i.get Remot eMac("192.168.0.3","192.168.0.1"));}} 。
C语言获取计算机的IP地址
C语言获取计算机的IP地址获取计算机的IP地址是计算机网络编程中的一个重要环节。
在C语言中,可以通过调用操作系统提供的网络相关的函数来获取IP地址。
下面将介绍在Windows和Linux操作系统上获取IP地址的方法。
一、Windows平台:Windows平台上获取IP地址可以使用Winsock库提供的函数。
下面是一个使用Winsock库获取IP地址的示例代码:```c#include <stdio.h>#include <winsock2.h>int maiWSADATA wsaData;int iResult;char hostname[256];struct hostent* host;char* ip;// 初始化Winsock库iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);if (iResult != 0)printf("WSAStartup failed: %d\n", iResult);return 1;}//获取本机主机名iResult = gethostname(hostname, sizeof(hostname));if (iResult != 0)printf("gethostname failed: %d\n", WSAGetLastError(); WSACleanup(;return 1;}//根据主机名获取主机信息host = gethostbyname(hostname);if (host == NULL)printf("gethostbyname failed: %d\n", WSAGetLastError(); WSACleanup(;return 1;}//获取IP地址字符串ip = inet_ntoa(*(struct in_addr*)host->h_addr_list[0]);printf("IP Address: %s\n", ip);// 释放Winsock库资源WSACleanup(;return 0;```该示例代码使用了Winsock库提供的函数`gethostname`和`gethostbyname`来获取本机主机名和主机信息,然后通过`inet_ntoa`函数将主机信息中的IP地址转换为字符串打印出来。
C语言获取Linux系统的IP地址和MAC地址
实际环境和特殊需求往往会将简单问题复杂化,比如计算机IP地址,对于一个连接中socket,可以直接获得本端和对端的IP、端口信息。
但在一些特殊场合我们可能需要更多的信息,比如系统中有几块网卡,他们的Mac地址是多少,每块网卡分配了几个IP(一个网卡对应多个IP)等等。
这些信息往往需要通过ifconfig指令来获得,对于程序员来说,在代码中调用外部的shell 指令可不是个最佳方案,因为没人能保障不同平台、不同版本的ifconfig指令输出的格式是一致的。
本篇文章中将介绍通过ioctl函数实现上述需求。
#includeint ioctl(int fd, int request, … );返回:成功返回0,失败返回-1ioctl函数的参数只有3个,但却是Unix中少有的几个“家族类”复杂函数,这里摘录一段《Unix网络编程》一书中对ioctl函数的描述:在传统上ioctl函数是用于那些普遍使用、但不适合归入其他类别的任何特殊的系统接口……网络程序(一般是服务器程序)中ioctl常用于在程序启动时获得主机上所有接口的信息:接口的地址、接口是否支持广播、是否支持多播,等等。
ioctl函数的第一个参数fd,可以表示一个打开的文件(文件句柄)或网络套接字,第二个和第三个参数体现了函数的家族特色,参数二request根据函数功能分类定义了多组宏,而参数三总是一个指针,指针的类型依赖于参数二request。
因为ioctl的种类实在太多,这里只列出和本文相关的几个参数定义:分类参数二(宏)参数三描述接口SIOCGIFCONF struct ifconf 获得所有接口列表SIOCGIFADDR struct ifreq 获得接口地址SIOCGIFFLAGS struct ifreq 获得接口标志SIOCGIFBRDADDR struct ifreq 获得广播地址SIOCGIFNETMASK struct ifreq 获得子网掩码上表中列出了两个相关的结构体:struct ifconf 和struct ifreq,要了解ioctl函数的具体运用,首先要了解这两个结构:struct ifconf{int ifc_len;union{__caddr_t ifcu_buf;struct ifreq *ifcu_req;} ifc_ifcu;};struct ifreq{# define IFHWADDRLEN 6# define IFNAMSIZ IF_NAMESIZEunion{char ifrn_name[IFNAMSIZ];} ifr_ifrn;union{struct sockaddr ifru_addr;struct sockaddr ifru_dstaddr;struct sockaddr ifru_broadaddr;struct sockaddr ifru_netmask;struct sockaddr ifru_hwaddr;short int ifru_flags;int ifru_ivalue;int ifru_mtu;struct ifmap ifru_map;char ifru_slave[IFNAMSIZ];char ifru_newname[IFNAMSIZ];__caddr_t ifru_data;} ifr_ifru;};struct ifconf的第二个元素ifc_ifcu是一个联合,是指向struct ifreq结构的地址,通常是一组struct ifreq结构空间(每一个描述一个接口),struct ifconf的第一个元素ifc_len描述了struct ifreq结构空间的大小;结构struct ifreq也有两个元素,第一个元素ifr_ifrn内含一个字符串,用来描述接口的名称,比如“eth0″、”wlan0”等,第二个元素是联合,比较复杂,用来描述套接口的地址结构。
C#--WinForm获取本机网卡的型号,IP地址,子网掩码和网关
string networkcardKeyName, deviceName;
string deviceServiceName, serviceName;
RegistryKey serviceNames = start.OpenSubKey(networkcardKey);
{
Console.WriteLine(" Gateway: {0}", defaultGateway);
}
networkKey.Close();
}
}
start.Close();
Console.ReadLine();
}
}
//方法二:使用WMI
//当然要先添加System.Management.dll的引用
using System;
using System.Management;
string[] subnets = (string[])mo["IPSubnet"];
string[] defaultgateways = (string[])mo["DefaultIPGateway"];
Console.WriteLine("Network Card: {0}", mo["Description"]);
}
foreach (string subnet in subnets)
{
Console.WriteLine(" Subnet Mask: {0}", subnet);
}
networkKey = start.OpenSubKey(serviceName);
获取本机名称和IP(VC++、MFC)
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
}
void CGetAddrDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CGetAddrDlg)
DDX_Text(pDX, IDC_HOSTNAME, m_sHostName);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
protected:
int StartUp();
int CleanUp();
int GetLocalHostName(CString& sHostName);
int GetIPAddress(const CString& sHostName,CString& sIPAddress);
提示:
1、本文档只为保存代码,不是供一步一步学习编程用的,故需要一定的基础,并需要一定的逆向逻辑推理。 ห้องสมุดไป่ตู้
2、工程,设置,连接,对象或库模块wsock32.lib
3、对话框,建立类向导。
#include <winsock2.h>
【GetAddrDlg.h】
0001-C语言如何获取ipv6地址
C语⾔如何获取ipv6地址written by whowin使⽤通常获取ipv4的IP地址的⽅法是⽆法获取ipv6地址的,本⽂介绍了使⽤C语⾔获取ipv6地址的三种⽅法,每种⽅法均给出了完整的源程序,本⽂所有实例在 ubuntu 20.04 下测试通过,gcc 版本 9.4.0。
1. ipv4的IP地址的获取⽅法不论是获取 ipv4 的 IP 地址还是 ipv6 的地址,应⽤程序都需要与内核通讯才可以完成;ioctl 是和内核通讯的⼀种常⽤⽅法,也是⽤来获取 ipv4 的 IP 地址的常⽤⽅法,下⾯代码演⽰了如何使⽤ioctl 来获取本机所有接⼝的 IP 地址:#include <stdio.h>#include <stdlib.h>#include <sys/ioctl.h>#include <linux/if.h>#include <arpa/inet.h>#include <sys/socket.h>int main() {int i=0;int sockfd;struct ifconf ifc;char buf[512] = {0};struct ifreq*ifr;ifc.ifc_len=512;ifc.ifc_buf=buf;if ((sockfd=socket(AF_INET, SOCK_DGRAM, 0)) <0) {perror("socket");return-1;}ioctl(sockfd, SIOCGIFCONF, &ifc);ifr= (struct ifreq*)buf;for (i= (ifc.ifc_len/sizeof(struct ifreq)); i>0; i--) {printf("%s: %s\n",ifr->ifr_name,inet_ntoa(((struct sockaddr_in*)&(ifr->ifr_addr))->sin_addr));ifr++;}}但是使⽤ ioctl ⽆法获取 ipv6 地址,即便我们建⽴⼀个 AF_INET6 的 socket,ioctl 仍然只返回 ipv4 的信息,我们可以试试下⾯代码;#include <stdio.h>#include <stdlib.h>图1:ioctl ⽆法获取ipv6地址这段程序在我的机器上的运⾏结果是这样的:我们看到,不管怎么折腾,返回的仍然只有 ipv4 的地址,所以我们需要⼀些其他的⽅法获得 ipv6 地址,下⾯介绍三种使⽤ C 语⾔获得 ipv6 地址的⽅法。
c#获得本地ip地址的三种方法
c#获得本地ip地址的三种⽅法⽹上有很多种⽅法可以获取到本地的IP地址。
⼀线常⽤的有这么些:枚举本地⽹卡using workInformation;using .Sockets;foreach (NetworkInterface netif in NetworkInterface.GetAllNetworkInterfaces().Where(a => a.SupportsMulticast).Where(a => a.OperationalStatus == OperationalStatus.Up).Where(a => workInterfaceType != NetworkInterfaceType.Loopback).Where(a => a.GetIPProperties().GetIPv4Properties() != null).Where(a => a.GetIPProperties().UnicastAddresses.Any(ua => ua.Address.AddressFamily == AddressFamily.InterNetwork)).Where(a => a.GetIPProperties().UnicastAddresses.Any(ua => ua.IsDnsEligible))){Console.WriteLine("Network Interface: {0}", );IPInterfaceProperties properties = netif.GetIPProperties();foreach (IPAddressInformation unicast in properties.UnicastAddresses)Console.WriteLine("\tUniCast: {0}", unicast.Address);}获得的信息⽐较全⾯,相当于⽹卡的信息都能获取,但是不能区分虚拟⽹卡(⽐如docker)。
C#获取本地计算机名,IP,MAC地址,硬盘ID
C#获取本地计算机名,IP,MAC地址,硬盘IDpublic string CpuID;public string MacAddress;public string DiskID;public string IpAddress;public string LoginUserName;public string ComputerName;public string SystemType;public string TotalPhysicalMemory; //单位:Mprivate static Computer _instance;public static Computer Instance(){if (_instance == null)_instance = new Computer();return _instance;}public Computer(){CpuID = GetCpuID();MacAddress = GetMacAddress();DiskID = GetDiskID();IpAddress = GetIPAddress();LoginUserName = GetUserName();SystemType = GetSystemType();TotalPhysicalMemory = GetTotalPhysicalMemory(); ComputerName = GetComputerName();}public string GetCpuID(){try{//获取CPU序列号代码string cpuInfo = "";//cpu序列号ManagementClass mc = new ManagementClass("Win32_Processor"); ManagementObjectCollection moc = mc.GetInstances();foreach (ManagementObject mo in moc){cpuInfo = mo.Properties["ProcessorId"].Value.ToString();}moc = null;mc = null;return cpuInfo;}catch{return "unknow";}finally{}}public string GetMacAddress(){try{//获取网卡硬件地址string mac = "";ManagementClass mc = newManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc){if ((bool)mo["IPEnabled"] == true){mac = mo["MacAddress"].ToString();break;}}moc = null;mc = null;return mac;}catch{return "unknow";}finally{}}public string GetIPAddress(){try{//获取IP地址string st = "";ManagementClass mc = newManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = mc.GetInstances();foreach (ManagementObject mo in moc){if ((bool)mo["IPEnabled"] == true){//st=mo["IpAddress"].ToString();System.Array ar;ar = (System.Array)(mo.Properties["IpAddress"].Value);st = ar.GetValue(0).ToString();break;}}moc = null;mc = null;return st;}catch{return "unknow";}finally{}}public string GetDiskID(){try{//获取硬盘IDString HDid = "";ManagementClass mc = new ManagementClass("Win32_DiskDrive"); ManagementObjectCollection moc = mc.GetInstances();foreach (ManagementObject mo in moc){HDid = (string)mo.Properties["Model"].Value;}moc = null;mc = null;return HDid;}catch{return "unknow";}finally{}}/// <summary>/// 操作系统的登录用户名/// </summary>/// <returns></returns>public string GetUserName(){try{string st = "";ManagementClass mc = new ManagementClass("Win32_ComputerSystem"); ManagementObjectCollection moc = mc.GetInstances();foreach (ManagementObject mo in moc){st = mo["UserName"].ToString();}moc = null;mc = null;return st;}catch{return "unknow";}finally{}}/// <summary>/// PC类型/// </summary>/// <returns></returns>public string GetSystemType(){try{string st = "";ManagementClass mc = new ManagementClass("Win32_ComputerSystem"); ManagementObjectCollection moc = mc.GetInstances();foreach (ManagementObject mo in moc){st = mo["SystemType"].ToString();}moc = null;mc = null;return st;}catch{return "unknow";}finally{}}/// <summary>/// 物理内存/// </summary>/// <returns></returns>public string GetTotalPhysicalMemory(){try{string st = "";ManagementClass mc = new ManagementClass("Win32_ComputerSystem"); ManagementObjectCollection moc = mc.GetInstances();foreach (ManagementObject mo in moc){st = mo["TotalPhysicalMemory"].ToString();}moc = null;mc = null;return st;}catch{return "unknow";}finally{}}/// <summary>////// </summary>/// <returns></returns>public string GetComputerName(){try{return System.Environment.GetEnvironmentVariable("ComputerName"); }catch{return "unknow";}finally{}。
c# 获取本机ip
using ;//方法一:string strHostIP = "";IPHostEntry oIPHost = Dns.Resolve(Environment.MachineName);if (oIPHost.AddressList.Length > 0)strHostIP = oIPHost.AddressList[0].ToString();//方法二:string ip = Dns.GetHostEntry(Dns.GetHostName()).AddressList[0].ToString();///完整版本Using System;Using System.Drawing;usingSystem.Collections;using ponentModel;using System.Windows.Forms;using System.Data;using ;namespace Network{///<summary>///Form1 的摘要说明。
///</summary>public class Form1 : System.Windows.Forms.Form {private bel label1;private System.Windows.Forms.TextBox textBox1;private bel label2;private System.Windows.Forms.TextBox textBox2;private System.Windows.Forms.Button button1;private System.Windows.Forms.Button button2;///<summary>///必需的设计器变量。
///</summary>private ponentModel.Container components=null;public Form1() {////Windows 窗体设计器支持所必需的//InitializeComponent();////TODO: 在InitializeComponent 调用后添加任何构造函数代码//}/// <summary>///清理所有正在使用的资源。