日期:2014-05-18  浏览次数:21149 次

udp,怎么样获得远端ip
远端电脑向我的电脑发送udp包,我电脑这怎样获得远端电脑的ip啊,跟踪接收数据的代码,RemoteEndPoint报错啊,错误是:"由于套接字没有连接并且(当使用一个 sendto 调用发送数据报套接字时)没有提供地址,发送或接收数据的请求没有被接受。"
  远端电脑发送udp包的代码是:
  UdpClient udpclient = new UdpClient();
  udpclient.Send(buf,buf.length,ip,port);
  udpclient.close();

------解决方案--------------------


兄弟,我得笑你下,因为我之前也遇到过类似的问题,你学UDP/TCP应该也不是很深~~

UDP接收到的包里就含有远端的IP等信息,调用函数就行啦:
public byte[] Receive(ref IPEndPoint remoteEP)
public byte[] EndReceive(IAsyncResult asyncResult, ref IPEndPoint remoteEP)
在你调用它们的时候要给出一参数啊,这个参数返回远程客户端的地址和端口。 


如果你想学深点的话,建议你去看看“UDP打洞技术”:
随便帮你找了篇://blog.163.com/renjianqin_1984/blog/static/132882154201053092157669/看懂之后你就可以深入了解UDP了~~
还可以编个类QQ出来~~
------解决方案--------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;

namespace QQServer
{
public partial class UDP : Component
{
private IPEndPoint ServerEndPoint = null; //定义网络端点
private UdpClient UDP_Server = new UdpClient(); //创建网络服务,也就是UDP的Socket
private System.Threading.Thread thdUdp; //创建一个线程
public delegate void DataArrivalEventHandler(byte[] Data, IPAddress Ip, int Port); //定义了一个托管方法
public event DataArrivalEventHandler DataArrival; //通过托管理在控件中定义一个事件
private string localHost = "10.0.0.1";
[Browsable(true), Category("Local"), Description("本地IP地址")] //在“属性”窗口中显示localHost属性
public string LocalHost
{
get { return localHost; }
set { localHost = value; }
}

private int localPort = 11000;
[Browsable(true), Category("Local"), Description("本地端口号")] //在“属性”窗口中显示localPort属性
public int LocalPort
{
get { return localPort; }
set { localPort = value; }
}

private bool active = false;
[Browsable(true), Category("Local"), Description("激活监听")] //在“属性”窗口中显示active属性
public bool Active
{
get { return active; }
set //该属性读取值

active = value;
if (active) //当值为True时
{
OpenSocket(); //打开监听
}
else
{
CloseSocket(); //关闭监听
}
}
}


public UDP(IContainer container)
{
container.Add(this);
}

protected void Listener() //监听
{
ServerEndPoint = new IPEndPoint(IPAddress.Any,localPort); //将IP地址和端口号以网络端点存储
if (UDP_Server != null)
UDP_Server.Close();
UDP_Server = new UdpClient(localPort); //创建一个新的端口号
UDP_Server.Client.ReceiveBufferSize = 1000000000; //接收缓冲区大小
UDP_Server.Client.SendBufferSize = 1000000000; //发送缓冲区大小

try
{
thdUdp = new Thread(new ThreadStart(GetUDPData)); //创建一个线程
thdUdp.Start(); //执行当前线程
}
catch (Exception e)
{
MessageBox.Show(e.ToString()); //显示线程的错误信息
}
}

private void GetUDPData() //获取当前接收的消息
{
while (active)
{
try