gpt4 book ai didi

c# - 尝试在 C# 中使用 INATExternalIPAddressCallback 获取 NAT 的外部 IP 地址

转载 作者:行者123 更新时间:2023-11-30 15:50:16 26 4
gpt4 key购买 nike

如何使用 Windows 库获取 NAT 的外部 IP 地址?我正在尝试查找有关 INATExternalIPAddressCallback 的任何信息,但只在 C++ 中找到一个使用不可用的 C# 接口(interface)的示例。任何指导将不胜感激。

-卡尔

最佳答案

抱歉,我没有使用来自 Windows 的使用 UPNP 服务的现有 API 来回答,但它可能对您有帮助

你也可以在互联网上使用 STUN 服务器,有很多开放的服务器,每个 VOIP 提供商都有一个。 http://en.wikipedia.org/wiki/STUN https://www.rfc-editor.org/rfc/rfc3489

例如打开一个 UDP 套接字,连接到端口 3478 上的 stun.gmx.net 并像这样发送一个数据包:

using System;
using System.Net;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;

namespace xxx
{
class STUNPacket
{
static RNGCryptoServiceProvider m_rand=new RNGCryptoServiceProvider();

private byte[] m_requestid=new byte[16];

public STUNPacket()
{
m_rand.GetBytes(m_requestid);
}

public byte[] CreateRequest()
{
byte[] packet=new byte[0x1c] {
//Header:
0x00,0x01, //Art des STUN-Pakets: 0x0001=Binding Request
0x00,0x08, //Länge des Pakets ohne Header
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, //Transkations-ID
//Message-Attribute:
0x00,0x03, //Typ: Change-Request
0x00,0x04, //Länge: 4 Bytes
0x00,0x00,0x00,0x00 //Weder IP, noch Port ändern
};

for(int i=0;i<16;i++)
packet[i+4]=m_requestid[i];

return packet;
}

public IPEndPoint ParseResponse(byte[] paket)
{
if (paket.Length<20)
throw new Exception("STUN-Response zu kurz, um einen Header zu haben");
if (paket[0]!=1||paket[1]!=1)
throw new Exception("STUN-Reposne hat falschen Typ, muss Binding-Response sein");
for (int i=0;i<16;i++)
if (paket[i+4]!=m_requestid[i])
throw new Exception("STUN-Antwort hat falsche Transkations-ID");
int size=paket[2]*256+paket[3];
int pos=20;
for(;;)
{
if (size<4)
throw new Exception("Verbleibende Nachricht zu kurz für weiteren Attributheader, "+
"Mapped-Adress-Attribut nicht gefunden");
int attrsize=paket[pos+2]*256+paket[pos+3];
if (pos+4+attrsize>paket.Length)
throw new Exception("Attributheader hat Länge, die nicht mehr ins Paket passt");
//Wenn kein Mapped-Adress-Attribut, dann überspringen
if (paket[pos]!=0||paket[pos+1]!=1)
{
pos+=attrsize;
continue;
}
if (attrsize<8)
throw new Exception("Mapped-Adress-Attribut ist zu kurz");
if (paket[pos+5]!=1)
throw new Exception("Adreßfamilie von Mapped-Adress ist nicht IPV4");
int port=paket[pos+6]*256+paket[pos+7];
IPAddress adress=new IPAddress(new byte[4] { paket[pos+8],paket[pos+9],paket[pos+10],paket[pos+11] });
return new IPEndPoint(adress,port);
}
}

}

ParseResponse 返回的 IP 地址应该是您在外界看到的 IP 地址。

请注意,如果没有互联网服务器的帮助或直接从您的服务器通过 upnp 将无法获取您的外部 ip

关于c# - 尝试在 C# 中使用 INATExternalIPAddressCallback 获取 NAT 的外部 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/799557/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com