Reputation: 3
i wanna ask about how can i use port for 2 application
for example i have a program like teamspeak server use port 9987 (Default)
and i have a code with c++ to listen to this udp ports and see the packets value
but the problem is when i start teamspeak server i can't start c++ code get error 10048
this is my code
#include <iostream>
#include <WS2tcpip.h>
// Include the Winsock library (lib) file
#pragma comment (lib, "ws2_32.lib")
using namespace std;
void main()
{
WSADATA data;
WORD version = MAKEWORD(2, 2);
// Start WinSock
int wsOk = WSAStartup(version, &data);
if (wsOk != 0)
{
// Not ok! Get out quickly
cout << "Can't start Winsock! " << wsOk;
return;
}
SOCKET in = socket(AF_INET, SOCK_DGRAM, 0);
sockaddr_in serverHint;
serverHint.sin_addr.S_un.S_addr = ADDR_ANY; // Us any IP address available on the machine
serverHint.sin_family = AF_INET; // Address format is IPv4
serverHint.sin_port = htons(9987); // Convert from little to big endian
int reuse = 1;
setsockopt(in, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse));
setsockopt(in, SOL_SOCKET, 15, (const char*)&reuse, sizeof(reuse));
// Try and bind the socket to the IP and port
if (bind(in, (sockaddr*)&serverHint, sizeof(serverHint)) == SOCKET_ERROR)
{
cout << "Can't bind socket! " << WSAGetLastError() << endl;
return;
}
sockaddr_in client; // Use to hold the client information (port / ip address)
int clientLength = sizeof(client); // The size of the client information
char buf[1024];
while (true)
{
ZeroMemory(&client, clientLength); // Clear the client structure
ZeroMemory(buf, 1024); // Clear the receive buffer
int bytesIn = recvfrom(in, buf, 1024, 0, (sockaddr*)&client, &clientLength);
if (bytesIn == SOCKET_ERROR)
{
cout << "Error receiving from client " << WSAGetLastError() << endl;
continue;
}
char clientIp[256]; // Create enough space to convert the address byte array
ZeroMemory(clientIp, 256); // to string of characters
inet_ntop(AF_INET, &client.sin_addr, clientIp, 256);
cout << "Message recv from " << clientIp << " : " << buf << endl;
}
closesocket(in);
WSACleanup();
}
i get this code from youtube channel and have some edit on it and i tired from search
my edit in the code is add SO_REUSEADDR and add SO_REUSEPORT and its value is 15
any one can help ?
Upvotes: 0
Views: 190
Reputation: 44238
2 separate applications cannot listen to the same port on the same address either for TCP or UDP, OS needs to know which application to deliver an UDP packet (or which app would accept connection in case of TCP). Exception is multicast UDP, but that is a different story. If you want to intercept packets that are delivered to existing application that is completely different task and significantly more complicated. You may use existing application like Wireshark or write your own app - details on writing app for traffic interception for windows can be found here Making a program that intercepts network traffic in Windows
Upvotes: 1