c#验证udp协议通信及实现端口扫描器
一、控制台实现udp通信
本次采用c/s模式创建应用实现通信。
1)创建项目
在VS2019中选择创建新项目,选择.net framework控制台应用,设置项目名并选择项目存储位置,然后点击创建,即可建立一个基本的控制台应用。
2)编写服务端
获取udp连接代码如下
UdpClient client = new UdpClient();
//设置目标ip地址,127.0.0.1为本地回环,即自己发给自己
IPAddress remoteIP = IPAddress.Parse("127.0.0.1");
//设置端口号
int remotePort = 11000;
IPEndPoint remotePoint = new IPEndPoint(remoteIP, remotePort);
发送数据使用client.Send(sendData, sendData.Length, remotePoint);
,在发送之前需要使用Encoding.Default.GetBytes
把将发送的数据转为16进制编码格式。
完整main函数代码如下:
//提示信息
Console.WriteLine("按下任意按键开始发送...");
Console.ReadKey();
int m;
//做好链接准备
UdpClient client = new UdpClient(); //实例一个端口
IPAddress remoteIP = IPAddress.Parse("127.0.0.1"); //假设发送给这个IP
int remotePort = 11000; //设置端口号
IPEndPoint remotePoint = new IPEndPoint(remoteIP, remotePort); //实例化一个远程端点
for (int i = 0; i < 50; i++)
{
//要发送的数据:第n行:hello cqjtu!重交物联2019级
string sendString = null;
sendString += "第";
m = i + 1;
sendString += m.ToString();
sendString += "行:hello cqjtu!重交物联2019级";
//定义发送的字节数组
//将字符串转化为字节并存储到字节数组中
byte[] sendData = null;
sendData = Encoding.Default.GetBytes(sendString);
client.Send(sendData, sendData.Length, remotePoint);//将数据发送到远程端点
}
client.Close();//关闭连接
//提示信息
Console.WriteLine("");
Console.WriteLine("数据发送成功,按任意键退出...");
System.Console.ReadKey();
3)编写客户端
同样创建一个新项目,main函数内代码如下
int result;
string str = "第50行:hello cqjtu!重交物联2019级";
UdpClient client = new UdpClient(11000);
string receiveString = null;