永发信息网

C# 写一个监听IP,端口的服务

答案:1  悬赏:30  手机版
解决时间 2021-04-14 03:44

C# 写一个监听IP,端口的服务

对于本机要支持
(local)
127.0.0.1
本机域名
IP地址

请问一下这个实现思路是怎样的。
谢谢啦...

最佳答案
using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;

public class GetSocket
{
private static Socket ConnectSocket(string server, int port)
{
Socket s = null;
IPHostEntry hostEntry = null;

// Get host related information.
hostEntry = Dns.GetHostEntry(server);

// Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
// an exception that occurs when the host IP Address is not compatible with the address family
// (typical in the IPv6 case).
foreach(IPAddress address in hostEntry.AddressList)
{
IPEndPoint ipe = new IPEndPoint(address, port);
Socket tempSocket =
new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

tempSocket.Connect(ipe);

if(tempSocket.Connected)
{
s = tempSocket;
break;
}
else
{
continue;
}
}
return s;
}

// This method requests the home page content for the specified server.
private static string SocketSendReceive(string server, int port)
{
string request = "GET / HTTP/1.1\r\nHost: " + server +
"\r\nConnection: Close\r\n\r\n";
Byte[] bytesSent = Encoding.ASCII.GetBytes(request);
Byte[] bytesReceived = new Byte[256];

// Create a socket connection with the specified server and port.
Socket s = ConnectSocket(server, port);

if (s == null)
return ("Connection failed");

// Send request to the server.
s.Send(bytesSent, bytesSent.Length, 0);

// Receive the server home page content.
int bytes = 0;
string page = "Default HTML page on " + server + ":\r\n";

// The following will block until te page is transmitted.
do {
bytes = s.Receive(bytesReceived, bytesReceived.Length, 0);
page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes);
}
while (bytes > 0);

return page;
}

public static void Main(string[] args)
{
string host;
int port = 80;

if (args.Length == 0)
// If no server name is passed as argument to this program,
// use the current host name as the default.
host = Dns.GetHostName();
else
host = args[0];

string result = SocketSendReceive(host, port);
Console.WriteLine(result);
}
}
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
台湾歌手张雨生最喜欢的人是谁?
怎么改QQ音乐里面歌的名字?
王者荣耀大乔台词有哪些
lol我是白银的低分段,比较喜欢蛮王和诺手,
谁给我几部好看的电影!!
windows7 7600GT X32为什么不能玩穿越火线
吃饭不吸收怎么办
(26分)阅读下列材料,结合所学知识回答问题。
木易百年上善痧道(银座大厦店)我想知道这个在
以金子与泥巴为话题的800字作文
我该怎么做才能让我女朋友的父母同意我们在一
墨竹手镯去哪里得
怎样玩智能手机才算会玩呢?(希望广大问友、
用万能器设置长虹D2983型,谁知道三位代码是多
TCL,L32E9BE怎么连WIFI
推荐资讯
大象的妊娠期是多少个月?
有什么命令可以直接区分诺基亚行货、水货、港
谭笑笑为了救叶潇答应了别人什么事
综合题(共6分)考试前夕,张强接到文学社长的
科比是不最好的篮球运动员?
介绍个VR视频教程网站
阅读下文,完成小题(22分)经典阅读观念的树
讲下文学哦.上课要用!
祖玛阁走错了怎么走,传奇里祖玛阁怎么走
2012年上半年,根据我国的物价、食品安全等,
我是新手,请问,停在别人的停车场,我的车怎
She always looks sad, makes people feel s
正方形一边上任一点到这个正方形两条对角线的
阴历怎么看 ?