上海东楼陆佳妮:C# 写一个监听IP,端口的服务
来源:百度文库 编辑:偶看新闻 时间:2024/05/10 06:53:33
C# 写一个监听IP,端口的服务
10[ 标签:c#,ip,端口 ]C# 写一个监听IP,端口的服务
对于本机要支持
(local)
127.0.0.1
本机域名
IP地址
请问一下这个实现思路是怎样的。
谢谢啦...
满意答案
好评率:66% 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);
}
}
c#写一个监听线程
c# 监听按钮的问题
internet信息服务在监听1049端口
在监听138监听目的ip***.***.***.*** 端口138
我的UDP端口不停监听一IP的53端口.为什么
bt的监听端口是什么意思
能监听端口的防火墙
BT的监听端口问题!
BT的监听端口问题!
天网的端口监听问题
我知道了一个私服的IP,可是我用登陆器上不去是怎么回事?我监听它的端口,可一直在变啊。。
我玩一个私服,找到它的IP,可是登陆不上去,我监听它的端口,可一直在变。。。
监听端口
BT的监听端口怎么设置?
请问交换机的监听端口怎么设置
bitcometV0.60最快的监听端口是什么?
BitComet0.6监听的端口号?
无法启动sql server 的监听端口
端口的状态为监听是什么含义?
BT的监听端口应该改为好多?????????????????
关与端口监听的问题
关与端口监听的问题
问一个关于c#开发的windows服务的问题
怎么看bt软件的端口?是不是那个监听端口?