c# - 以编程方式从网络接口(interface)发送数据

标签 c# windows winforms network-programming

我有一个端口查询应用程序,用于检查远程端口是打开还是阻塞。我想要做的是在进行端口检查时,能够选择本地机器上的哪个网络接口(interface)来发送流量。这可能吗?我该怎么做?

更新:

我已经添加了以下几行,但它仍然没有绑定(bind)

    string localip; 
    localip = interfacesComboBox.Text; 
    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
socket.ReceiveTimeout = 1000; 
IPAddress myIP = IPAddress.Parse(localip); 
socket.Bind(new IPEndPoint(myIP, 0));

最佳答案

    private ushort BindToNextAvail(Socket sock, params ushort[] portList)
    {
        foreach (ushort i in portList)
        {
            try
            {
                sock.Bind(new IPEndPoint(IPAddress.Any, i));
                return (ushort)((IPEndPoint)sock.LocalEndPoint).Port;
            }
            catch
            {
                Logger.Instance().WriteLog(EventLogEntryType.Warning, "Unable to use port " + i.ToString());
            }
        }

        return 0;
    }

那是我的实时应用程序,所以它应该大致适合你。

以及该方法调用位置的示例:

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.ReceiveTimeout = 1000;

if (Bind(socket, 10000, 10001, 10002) == 0)
    throw new SocketException(10049); // "Cannot assign requested address" exception

关于c# - 以编程方式从网络接口(interface)发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8611386/

相关文章:

c# - 检索具有 CLSID 的组件的 COM 类工厂 - 类未注册

.net - Windows 窗体和 ShowDialog 问题

c# - WinForms C# - 自由绘制的正确方法?

c# - 更新异常 : Operation is not valid due to the current state of the object when using Entity Framework and Oracle

c# - 为 POST API 请求发回多个响应

c# - FirstOrDefault 扩展方法如何工作?

python - ffmpeg 无法检测文件,而 os 可以

windows - 替换字符串中的字符

c# - 根据参数为 C# 字符串数组赋值

c# - 绑定(bind)和x :Bind problems with TwoWay mode