C# 使用UdpClient给指定IP地址发送数据
时间: 2023-08-07 20:06:47 浏览: 115
您可以使用以下代码示例在 C# 中使用 UdpClient 给指定 IP 地址发送数据:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class Program
{
static void Main(string[] args)
{
// 目标 IP 地址和端口号
string ipAddress = "192.168.0.100";
int port = 1234;
// 创建 UdpClient 实例
UdpClient udpClient = new UdpClient();
try
{
// 将要发送的数据转换为字节数组
string message = "Hello, World!";
byte[] data = Encoding.UTF8.GetBytes(message);
// 发送数据
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);
udpClient.Send(data, data.Length, endPoint);
Console.WriteLine("数据发送成功。");
}
catch (Exception e)
{
Console.WriteLine("数据发送失败:" + e.Message);
}
finally
{
// 关闭 UdpClient 实例
udpClient.Close();
}
Console.ReadKey();
}
}
```
在上述代码中,您需要替换 `ipAddress` 和 `port` 变量的值为您要发送数据的目标 IP 地址和端口号。然后将要发送的数据转换为字节数组,使用 UdpClient 的 `Send` 方法发送数据。最后,关闭 UdpClient 实例。
阅读全文
相关推荐















