我无法将非本地IP地址绑定到套接字

时间:2016-06-30 14:09:41

标签: c#

static void Main(string[] args)
{
    try
    {
        Socket  socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);

        string GETrequest = "GET / HTTP/1.1\r\nHost: 172.16.9.251\r\nConnection: keep-alive\r\nAccept: text/html\r\nUser-Agent: CSharpTests\r\n\r\n";

        IPEndPoint g_source = new IPEndPoint(IPAddress.Parse("172.16.9.251"), 0);//not my local ip address

        socket.SetSocketOption(SocketOptionLevel.IP,  //Applies only to IP packets
                     SocketOptionName.HeaderIncluded, //Set the include header
                           true);

        //when we bind I getting error for "The requested address is not valid in its context"
        socket.Bind(g_source);

        socket.Connect(new IPEndPoint(IPAddress.Parse("172.16.9.251"), 80));

        socket.Send(Encoding.ASCII.GetBytes(GETrequest), Encoding.ASCII.GetBytes(GETrequest).Length,SocketFlags.None);
        socket.Close();
    }
    catch (Exception ex)
    {

    }
}

1 个答案:

答案 0 :(得分:0)

可能你的意思是这个:

IPEndPoint g_source = new IPEndPoint(IPAddress.Parse("172.16.9.251"), 80);

而不是

IPEndPoint g_source = new IPEndPoint(IPAddress.Parse("172.16.9.251"), 0);

如果您使用端口0,系统将为您分配1024-5000之间的随机端口。 https://msdn.microsoft.com/en-us/library/system.net.sockets.socket.bind(v=vs.110).aspx