C# 获取本机外网IP

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# 获取本机外网IP相关的知识,希望对你有一定的参考价值。

我想获取本机的外网IP(桌面应用程序)
Dns类里有个GetHostEntry方法能获取IP!
但是获取的是个列表,里面有外网IP,也有内网ip!
我试着把内网IP过滤掉(有10开头的,192.168开头,172.16-172.31开头)

可是又蹦出一个169.254开头的本地IP!

我不想用过滤了,感觉不太保险!
怎么直接获取本机的外网IP?用windows Api也行

using System;
using System.Runtime.InteropServices ;
using System.Collections.Generic ;
using System.Net ;
using System.Net.Sockets ;
using System.IO ;
using ESBasic.Helpers ;
using ESBasic.Network.Tcp;

namespace ESBasic.Network

/// <summary>
/// NetHelper 。
/// </summary>
public static class NetHelper

#region IsPublicIPAddress
public static bool IsPublicIPAddress(string ip)

if(ip.StartsWith("10.")) //A类 10.0.0.0到10.255.255.255.255

return false ;


if(ip.StartsWith("172."))//B类 172.16.0.0到172.31.255.255

if(ip.Substring(6 ,1) == ".")

int secPart = int.Parse(ip.Substring(4 ,2)) ;
if((16 <= secPart) && (secPart <= 31) )

return false ;




if(ip.StartsWith("192.168."))//C类 192.168.0.0到192.168.255.255

return false ;


return true ;

#endregion

#region ReceiveData
/// <summary>
/// ReceiveData 从网络读取指定长度的数据
/// </summary>
public static byte[] ReceiveData(NetworkStream stream ,int size)

byte[] result = new byte[size] ;

NetHelper.ReceiveData(stream ,result ,0 ,size) ;

return result ;


/// <summary>
/// ReceiveData 从网络读取指定长度的数据 ,存放在buff中offset处
/// </summary>
public static void ReceiveData(NetworkStream stream ,byte[] buff ,int offset ,int size)

int readCount = 0 ;
int totalCount = 0 ;
int curOffset = offset ;

while(totalCount < size)

int exceptSize = size - totalCount ;
readCount = stream.Read(buff ,curOffset ,exceptSize) ;
if(readCount == 0)

throw new IOException("NetworkStream Interruptted !") ;

curOffset += readCount ;
totalCount += readCount ;



/// <summary>
/// ReceiveData 从网络读取指定长度的数据
/// </summary>
public static byte[] ReceiveData(ISafeNetworkStream stream ,int size)

byte[] result = new byte[size] ;

NetHelper.ReceiveData(stream ,result ,0 ,size) ;

return result ;


/// <summary>
/// ReceiveData 从网络读取指定长度的数据 ,存放在buff中offset处
/// </summary>
public static void ReceiveData(ISafeNetworkStream stream, byte[] buff, int offset, int size)

int readCount = 0 ;
int totalCount = 0 ;
int curOffset = offset ;

while(totalCount < size)

int exceptSize = size - totalCount ;
readCount = stream.Read(buff ,curOffset ,exceptSize) ;
if(readCount == 0)

throw new IOException("NetworkStream Interruptted !") ;

curOffset += readCount ;
totalCount += readCount ;


#endregion

#region GetRemotingHanler
//前提是已经注册了remoting通道
public static object GetRemotingHanler(string channelTypeStr ,string ip ,int port ,string remotingServiceName ,Type destInterfaceType)

try

string remoteObjUri = string.Format("0://1:2/3" ,channelTypeStr ,ip ,port ,remotingServiceName) ;
return Activator.GetObject(destInterfaceType ,remoteObjUri);

catch

return null ;


#endregion

#region GetLocalIp
/// <summary>
/// GetLocalIp 获取本机的IP地址
/// </summary>
public static IPAddress[] GetLocalIp()

string hostName = Dns.GetHostName() ;
IPHostEntry hEntry = Dns.Resolve(hostName) ;

return hEntry.AddressList ;


public static IPAddress GetFirstLocalIp()

string hostName = Dns.GetHostName();
IPHostEntry hEntry = Dns.Resolve(hostName);

return hEntry.AddressList[0];


/// <summary>
/// GetLocalPublicIp 获取本机的公网IP地址
/// </summary>
public static string GetLocalPublicIp()

IPAddress[] list = NetHelper.GetLocalIp();
foreach(IPAddress ip in list)

if(NetHelper.IsPublicIPAddress(ip.ToString()))

return ip.ToString() ;



return null ;

#endregion

#region IsConnectedToInternet
/// <summary>
/// IsConnectedToInternet 机器是否联网
/// </summary>
public static bool IsConnectedToInternet()

int Desc=0;
return InternetGetConnectedState(Desc,0);


[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(int Description,int ReservedValue);
#endregion

#region GetMacAddress 获取网卡mac地址
/// <summary>
/// GetMacAddress 获取本机所有网卡的Mac地址
/// </summary>
public static IList<string> GetMacAddress()

return MachineHelper.GetMacAddress();

#endregion

#region DownLoadFileFromUrl
/// <summary>
/// DownLoadFileFromUrl 将url处的文件下载到本地
/// </summary>
public static void DownLoadFileFromUrl(string url ,string saveFilePath)

FileStream fstream = new FileStream(saveFilePath ,FileMode.Create ,FileAccess.Write);
WebRequest wRequest = WebRequest.Create(url);

try

WebResponse wResponse = wRequest.GetResponse();
int contentLength =(int)wResponse.ContentLength;

byte[] buffer = new byte[1024];
int read_count = 0 ;
int total_read_count = 0 ;
bool complete = false;

while (!complete )

read_count = wResponse.GetResponseStream().Read(buffer,0,buffer.Length);

if(read_count > 0)

fstream.Write(buffer ,0 ,read_count) ;
total_read_count += read_count ;

else

complete = true ;



fstream.Flush() ;

finally

fstream.Close() ;
wRequest = null;


#endregion



这个类直接拿去用吧,命名空间改一下,里面有你想要的方法以及一些可能对你有用的方法
参考技术A 不可以直接获取外网IP的。除非你本身就是拨号上网,没有通过家用路由器分接。

http://zhidao.baidu.com/question/149330561.html

这个问题我也回答过了%
参考技术B 我也遇到这个问题 求解决方法

获取本机外网IP的工具类

ExternalIpAddressFetcher.java

package com.tyust.common;
import java.io.IOException;  
import java.io.InputStream;  
import java.net.HttpURLConnection;  
import java.net.MalformedURLException;  
import java.net.URL;  
import java.util.regex.Matcher;  
import java.util.regex.Pattern;  
  
/** 
 * 获取本机外网IP地址 
 * 思想是访问网站http://checkip.dyndns.org/,得到返回的文本后解析出本机在外网的IP地址 
 * @author Administrator 
 * 
 */  
public class ExternalIpAddressFetcher {  
    // 外网IP提供者的网址  
    private String externalIpProviderUrl;  
  
    // 本机外网IP地址  
    private String myExternalIpAddress;  
  
    public ExternalIpAddressFetcher(String externalIpProviderUrl) {  
        this.externalIpProviderUrl = externalIpProviderUrl;  
  
        String returnedhtml = fetchExternalIpProviderHTML(externalIpProviderUrl);  
          
        parse(returnedhtml);  
    }  
  
    /** 
     * 从外网提供者处获得包含本机外网地址的字符串 
     * 从http://checkip.dyndns.org返回的字符串如下 
     * <html><head><title>Current IP Check</title></head><body>Current IP Address: 123.147.226.222</body></html> 
     * @param externalIpProviderUrl 
     * @return 
     */  
    private String fetchExternalIpProviderHTML(String externalIpProviderUrl) {  
        // 输入流  
        InputStream in = null;  
          
        // 到外网提供者的Http连接  
        HttpURLConnection httpConn = null;  
  
        try {  
            // 打开连接  
            URL url = new URL(externalIpProviderUrl);  
            httpConn = (HttpURLConnection) url.openConnection();  
                          
            // 连接设置  
            HttpURLConnection.setFollowRedirects(true);  
            httpConn.setRequestMethod("GET");  
            httpConn.setRequestProperty("User-Agent",  
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)");  
  
            // 获取连接的输入流  
            in = httpConn.getInputStream();  
            byte[] bytes=new byte[1024];// 此大小可根据实际情况调整  
              
            // 读取到数组中  
            int offset = 0;  
            int numRead = 0;  
            while (offset < bytes.length  
                   && (numRead=in.read(bytes, offset, bytes.length-offset)) >= 0) {  
                offset += numRead;  
            }  
              
            // 将字节转化为为UTF-8的字符串          
            String receivedString=new String(bytes,"UTF-8");  
              
            // 返回  
            return receivedString;  
        } catch (MalformedURLException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                in.close();  
                httpConn.disconnect();  
            } catch (Exception ex) {  
                ex.printStackTrace();  
            }  
        }  
  
        // 出现异常则返回空  
        return null;  
    }  
      
    /** 
     * 使用正则表达式解析返回的HTML文本,得到本机外网地址 
     * @param html 
     */  
    private void parse(String html){  
        Pattern pattern=Pattern.compile("(\\\\d{1,3})[.](\\\\d{1,3})[.](\\\\d{1,3})[.](\\\\d{1,3})", Pattern.CASE_INSENSITIVE);      
        Matcher matcher=pattern.matcher(html);          
        while(matcher.find()){  
            myExternalIpAddress=matcher.group(0);  
        }      
    }      
  
    /** 
     * 得到本机外网地址,得不到则为空 
     * @return 
     */  
    public String getMyExternalIpAddress() {  
        return myExternalIpAddress;  
    }  
      
    public static void main(String[] args){  
        ExternalIpAddressFetcher fetcher=new ExternalIpAddressFetcher("http://checkip.dyndns.org/");  
          
        System.out.println(fetcher.getMyExternalIpAddress());  
    }  
}  

 

 

 也可以直接访问网站:

技术分享图片

 

以上是关于C# 获取本机外网IP的主要内容,如果未能解决你的问题,请参考以下文章

请问 C# 如何获取外网IP?

怎么实现c#获取ip内网,外网地址?

vc获取本机外网IP,怎么获取,求源码。

java中如何获取到本机的外网ip地址?

获取本机外网IP 更新到D盘的文件 追500高分

获取本机外网ip和内网ip