怎样自动获取本机的Port号(端口号)

时间:2021-09-04 18:11:06
我在写一个有关Soctet的程序,不知怎样才能自动获取本机的Port号(端口号)。

6 个解决方案

#1


IPHostEntry ipe = Dns.GetHostByName(Dns.GetHostName());
如果有地址,就是ipe.AddressList[0]

#2


TO :  xixigongzhu(夕夕公主)
这样是获取本机IP地止而不是本机的Port端口号。

#3


获取本机端口号?  本机上有上千的端口号,你要哪个?

#4


IPEndPoint ip = (IPEndPoint) socket.LocalEndPoint;
int port = ip.Port;

#5


IPHostEntry ipe = Dns.GetHostByName(Dns.GetHostName());

#6


private void btnStart_Click(object sender, System.EventArgs e)
{
try
{
IPHostEntry myHost = new IPHostEntry();
myHost = Dns.GetHostByName(txtServer.Text);
string IPstring = myHost.AddressList[0].ToString();
myIP = IPAddress.Parse(IPstring);
}
catch
{
MessageBox.Show("您输入的IP地址格式不正确,请重新输入!");
}

try
{
myServer = new IPEndPoint(myIP,Int32.Parse(txtPort.Text.Trim()));
mySocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
mySocket.Bind(myServer);
mySocket.Listen(50);

txtState.Text = "主机"+txtServer.Text+"端口"+txtPort.Text+"开始监听.....";

//线程
Thread thread = new Thread(new ThreadStart(target));
thread.Start();
}
catch(Exception ee)
{
txtState.Text = ee.Message;
}

}//end btnStart_Click

//线程同步方法target
private void target()
{
while(true)
{
//设为非终止
myReset.Reset();

mySocket.BeginAccept(new AsyncCallback(AcceptCallback),mySocket);

//阻塞当前线程,直到收到请求信号
myReset.WaitOne();
}
}//end target

//异步回调方法AcceptCallback
private void AcceptCallback(IAsyncResult ar)
{
//将事件设为终止
myReset.Set();

Socket listener = (Socket)ar.AsyncState;
handler = listener.EndAccept(ar);

//获取状态
StateObject state = new StateObject();
state.workSocket = handler;

txtState.Text = "与客户建立连接。\r\n";

ListViewItem item ;
//向lvIncept控件写入一条新进入的客户信息
string[] itemName = new string[3];
itemName[0] = handler.RemoteEndPoint.ToString(); 
itemName[1] = DateTime.Now.ToString(); 
itemName[2] = "正在连通状态.................................................";
item = new ListViewItem(itemName,0);
item.Checked=false;

//统计连接客户端数
intClient++;
txtCount.Text = intClient.ToString();

lvIncept.Items.Add(item);

try
{
byte[] byteData = System.Text.Encoding.UTF8.GetBytes("已经准备好,请通话!"+"\r\n");
//开始发送
handler.BeginSend(byteData,0,byteData.Length,0,new AsyncCallback(SendCallback),handler);
}
catch(Exception ee)
{
MessageBox.Show(ee.Message);
}

//线程
Thread thread = new Thread(new ThreadStart(begReceive));
thread.Start();

}//end AcceptCallback

//异步回调方法 SendCallback
private void SendCallback(IAsyncResult ar)
{
try
{
handler = (Socket)ar.AsyncState;
int bytesSent = handler.EndSend(ar);
}
catch(Exception ee)
{
MessageBox.Show(ee.Message);
}

}//end SendCallback

//线程同步方法begReceive
private void begReceive()
{
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer,0,StateObject.BufferSize,0,new AsyncCallback(ReadCallback),state);

//中断指定的客户端
if(ClickBreak)
{
BreakClient(ref handler);
}

string strAccept = "";
strAccept = state.sb.Append(System.Text.Encoding.UTF8.GetString(state.buffer,0,24)).ToString();
//sw.Write(handler.RemoteEndPoint.ToString()+":");
sw.WriteLine(strAccept);
//MessageBox.Show(strAccept);
txtSend.Text = strAccept;
sw.Flush();

}//end begReceive

//异步回调方法ReadCallback
private void ReadCallback(IAsyncResult ar)
{
StateObject state = (StateObject) ar.AsyncState;
Socket tt = state.workSocket;

//重新开始读取数据
try
{
//结束读取并获取读取字节数
//int bytesRead = handler.EndReceive(ar);
int bytesRead = tt.EndReceive(ar);
state.sb.Append(System.Text.Encoding.UTF8.GetString(state.buffer,0,bytesRead));
string content = state.sb.ToString();
state.sb.Remove(0,content.Length);

//txtSend.Text = content;
textBox1.AppendText(tt.RemoteEndPoint.ToString()+": "+content+"\r\n");

tt.BeginReceive(state.buffer,0,StateObject.BufferSize,0,new AsyncCallback(ReadCallback),state);
}
catch
{
//从lvIncept控件删除相应的信息
if(ClickBreak == false)
{
for(int i=0;i<lvIncept.Items.Count;i++)
{
if(lvIncept.Items[i].SubItems[0].Text == tt.RemoteEndPoint.ToString())
{
lvIncept.Items[i].Remove();
}
}
}

intClient--;
txtCount.Text = intClient.ToString();
}

//控制颜色
CortrolColor(ref lvIncept);

}//end ReadCallback

//发送信息
private void SendMessage(string strSend)
{
try
{
byte[] byteData = System.Text.Encoding.UTF8.GetBytes(strSend);

/*
for(int i = 0;i<lvIncept.Items.Count;i++)
{
if(lvIncept.Items[i].Checked)
{
if(lvIncept.Items[i].SubItems[0].Text == handler.RemoteEndPoint.ToString())
{
//开始发送数据
handler.BeginSend(byteData,0,byteData.Length,0,new AsyncCallback(SendCallback),handler);
}
}
}
*/

//开始发送数据
handler.BeginSend(byteData,0,byteData.Length,0,new AsyncCallback(SendCallback),handler);
}
catch(Exception ee)
{
MessageBox.Show(ee.Message);
}

}//end SendMessage

#1


IPHostEntry ipe = Dns.GetHostByName(Dns.GetHostName());
如果有地址,就是ipe.AddressList[0]

#2


TO :  xixigongzhu(夕夕公主)
这样是获取本机IP地止而不是本机的Port端口号。

#3


获取本机端口号?  本机上有上千的端口号,你要哪个?

#4


IPEndPoint ip = (IPEndPoint) socket.LocalEndPoint;
int port = ip.Port;

#5


IPHostEntry ipe = Dns.GetHostByName(Dns.GetHostName());

#6


private void btnStart_Click(object sender, System.EventArgs e)
{
try
{
IPHostEntry myHost = new IPHostEntry();
myHost = Dns.GetHostByName(txtServer.Text);
string IPstring = myHost.AddressList[0].ToString();
myIP = IPAddress.Parse(IPstring);
}
catch
{
MessageBox.Show("您输入的IP地址格式不正确,请重新输入!");
}

try
{
myServer = new IPEndPoint(myIP,Int32.Parse(txtPort.Text.Trim()));
mySocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
mySocket.Bind(myServer);
mySocket.Listen(50);

txtState.Text = "主机"+txtServer.Text+"端口"+txtPort.Text+"开始监听.....";

//线程
Thread thread = new Thread(new ThreadStart(target));
thread.Start();
}
catch(Exception ee)
{
txtState.Text = ee.Message;
}

}//end btnStart_Click

//线程同步方法target
private void target()
{
while(true)
{
//设为非终止
myReset.Reset();

mySocket.BeginAccept(new AsyncCallback(AcceptCallback),mySocket);

//阻塞当前线程,直到收到请求信号
myReset.WaitOne();
}
}//end target

//异步回调方法AcceptCallback
private void AcceptCallback(IAsyncResult ar)
{
//将事件设为终止
myReset.Set();

Socket listener = (Socket)ar.AsyncState;
handler = listener.EndAccept(ar);

//获取状态
StateObject state = new StateObject();
state.workSocket = handler;

txtState.Text = "与客户建立连接。\r\n";

ListViewItem item ;
//向lvIncept控件写入一条新进入的客户信息
string[] itemName = new string[3];
itemName[0] = handler.RemoteEndPoint.ToString(); 
itemName[1] = DateTime.Now.ToString(); 
itemName[2] = "正在连通状态.................................................";
item = new ListViewItem(itemName,0);
item.Checked=false;

//统计连接客户端数
intClient++;
txtCount.Text = intClient.ToString();

lvIncept.Items.Add(item);

try
{
byte[] byteData = System.Text.Encoding.UTF8.GetBytes("已经准备好,请通话!"+"\r\n");
//开始发送
handler.BeginSend(byteData,0,byteData.Length,0,new AsyncCallback(SendCallback),handler);
}
catch(Exception ee)
{
MessageBox.Show(ee.Message);
}

//线程
Thread thread = new Thread(new ThreadStart(begReceive));
thread.Start();

}//end AcceptCallback

//异步回调方法 SendCallback
private void SendCallback(IAsyncResult ar)
{
try
{
handler = (Socket)ar.AsyncState;
int bytesSent = handler.EndSend(ar);
}
catch(Exception ee)
{
MessageBox.Show(ee.Message);
}

}//end SendCallback

//线程同步方法begReceive
private void begReceive()
{
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer,0,StateObject.BufferSize,0,new AsyncCallback(ReadCallback),state);

//中断指定的客户端
if(ClickBreak)
{
BreakClient(ref handler);
}

string strAccept = "";
strAccept = state.sb.Append(System.Text.Encoding.UTF8.GetString(state.buffer,0,24)).ToString();
//sw.Write(handler.RemoteEndPoint.ToString()+":");
sw.WriteLine(strAccept);
//MessageBox.Show(strAccept);
txtSend.Text = strAccept;
sw.Flush();

}//end begReceive

//异步回调方法ReadCallback
private void ReadCallback(IAsyncResult ar)
{
StateObject state = (StateObject) ar.AsyncState;
Socket tt = state.workSocket;

//重新开始读取数据
try
{
//结束读取并获取读取字节数
//int bytesRead = handler.EndReceive(ar);
int bytesRead = tt.EndReceive(ar);
state.sb.Append(System.Text.Encoding.UTF8.GetString(state.buffer,0,bytesRead));
string content = state.sb.ToString();
state.sb.Remove(0,content.Length);

//txtSend.Text = content;
textBox1.AppendText(tt.RemoteEndPoint.ToString()+": "+content+"\r\n");

tt.BeginReceive(state.buffer,0,StateObject.BufferSize,0,new AsyncCallback(ReadCallback),state);
}
catch
{
//从lvIncept控件删除相应的信息
if(ClickBreak == false)
{
for(int i=0;i<lvIncept.Items.Count;i++)
{
if(lvIncept.Items[i].SubItems[0].Text == tt.RemoteEndPoint.ToString())
{
lvIncept.Items[i].Remove();
}
}
}

intClient--;
txtCount.Text = intClient.ToString();
}

//控制颜色
CortrolColor(ref lvIncept);

}//end ReadCallback

//发送信息
private void SendMessage(string strSend)
{
try
{
byte[] byteData = System.Text.Encoding.UTF8.GetBytes(strSend);

/*
for(int i = 0;i<lvIncept.Items.Count;i++)
{
if(lvIncept.Items[i].Checked)
{
if(lvIncept.Items[i].SubItems[0].Text == handler.RemoteEndPoint.ToString())
{
//开始发送数据
handler.BeginSend(byteData,0,byteData.Length,0,new AsyncCallback(SendCallback),handler);
}
}
}
*/

//开始发送数据
handler.BeginSend(byteData,0,byteData.Length,0,new AsyncCallback(SendCallback),handler);
}
catch(Exception ee)
{
MessageBox.Show(ee.Message);
}

}//end SendMessage