TCP / IP 패킷 리스너
-
13-12-2019 - |
문제
기본적인 네트워크 프로그래밍을 시작했습니다.
TcpClient
및 TcpListener
를 사용하여 내 자신의 프로그램을 읽고 작성했으며 잘 작동했습니다.
그러나 내가 지금 일하고있는 응용 프로그램은 조금 다르게 작동합니다.
연결하지 않고도 TCP / IP 패킷을 청취하는 프로그램을 설정하고 싶습니다.
예를 들어 패킷 전송 앱이 적절한 IP 추가 및 포트 번호로 내 프로그램에 패킷을 보냅니다.
또한 SharpPCAP 및 Packet.net을 사용하여 삽입했지만 모든 예제는 로컬에서 발견 된 장치에서만 듣는 모든 예제 (포트 번호 및 IP 추가와 같은 매개 변수를 설정할 수있는 기회가 없음)입니다.
누구 든지이 작업을 수행하는 방법에 대한 제안이 있습니까?
해결책
TCP / IP 대신 UDP 프로토콜 사용을 살펴보아야합니다.
http:///en.wikipedia.org/wiki/user_datagram_protocol
여기 클라이언트의 코드입니다.
using System.Net;
using System.Net.Sockets;
...
/// <summary>
/// Sends a sepcified number of UDP packets to a host or IP Address.
/// </summary>
/// <param name="hostNameOrAddress">The host name or an IP Address to which the UDP packets will be sent.</param>
/// <param name="destinationPort">The destination port to which the UDP packets will be sent.</param>
/// <param name="data">The data to send in the UDP packet.</param>
/// <param name="count">The number of UDP packets to send.</param>
public static void SendUDPPacket(string hostNameOrAddress, int destinationPort, string data, int count)
{
// Validate the destination port number
if (destinationPort < 1 || destinationPort > 65535)
throw new ArgumentOutOfRangeException("destinationPort", "Parameter destinationPort must be between 1 and 65,535.");
// Resolve the host name to an IP Address
IPAddress[] ipAddresses = Dns.GetHostAddresses(hostNameOrAddress);
if (ipAddresses.Length == 0)
throw new ArgumentException("Host name or address could not be resolved.", "hostNameOrAddress");
// Use the first IP Address in the list
IPAddress destination = ipAddresses[0];
IPEndPoint endPoint = new IPEndPoint(destination, destinationPort);
byte[] buffer = Encoding.ASCII.GetBytes(data);
// Send the packets
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
for(int i = 0; i < count; i++)
socket.SendTo(buffer, endPoint);
socket.Close();
}
. 제휴하지 않습니다 StackOverflow