Powiązanie z określonym adresem IP i portem w celu odebrania danych UDP
Próbuję odbierać dane UDP, które są nadawane na adres sieciowy 192.168.103.255 port 3000 przez PlayCap (http://www.signal11.us/oss/playcap/). Mam problemy z powiązaniem z tym adresem i portem. Oto mój kod Java:
public static void main(String[] args) {
try {
DatagramSocket s = new DatagramSocket();
InetSocketAddress address = new InetSocketAddress("192.168.103.255", 3000);
s.bind(address);
byte buffer[] = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
System.out.println("Waiting...");
s.receive(packet);
System.out.println("Received!");
} catch (Exception e) {
e.printStackTrace();
}
}
Zwraca błąd:
java.net.SocketException: already bound
at java.net.DatagramSocket.bind(Unknown Source)
at runner.main(runner.java:12)
Uruchomiłem polecenie „netstat -a -n”, a ani adres 192.168.103.255, ani port 3000 nie są wyświetlane w żadnym miejscu na wyjściu, więc nie sądzę, aby ten port był już używany. W rzeczywistości otrzymuję ten błąd dla dowolnej kombinacji adresu / portu, którą próbuję (w tym mojego statycznego adresu IP).
Napisałem także kod C, aby utworzyć gniazdo i powiązać go z tym adresem i portem, ale również zawodzi w wywołaniu połączenia. Ten kod wiąże jednak z portami mój statyczny adres IP (192.168.1.149). Oto ten kod:
#include <stdio.h>
#include <sys/types.h>
#include <winsock.h>
#include <unistd.h>
#define a1 192
#define a2 168
#define a3 103
#define a4 255
#define PORT 3000
int main() {
/* Open windows connection */
WSADATA w;
if (WSAStartup(0x0101, &w) != 0)
{
printf("Could not open Windows connection.\n");
exit(0);
}
/* Clear out server struct */
SOCKADDR_IN server;
memset((void *)&server, '\0', sizeof(struct sockaddr_in));
/* Set family and port */
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
server.sin_addr.S_un.S_un_b.s_b1 = (unsigned char)a1;
server.sin_addr.S_un.S_un_b.s_b2 = (unsigned char)a2;
server.sin_addr.S_un.S_un_b.s_b3 = (unsigned char)a3;
server.sin_addr.S_un.S_un_b.s_b4 = (unsigned char)a4;
/* Open a datagram socket */
int sd = socket(AF_INET, SOCK_DGRAM, 0);
if (sd == INVALID_SOCKET)
{
printf("Could not create socket.\n");
WSACleanup();
exit(0);
}
/* Bind address to socket */
if (bind(sd, (struct sockaddr *)&server, sizeof(SOCKADDR_IN)) == -1)
{
printf("Could not bind name to socket.\n");
closesocket(sd);
WSACleanup();
exit(0);
}
/* Receive */
char data[1024];
printf("Waiting to receive...\n");
if (recv(sd, (char *)&data, (int)sizeof(data), 0))
{
printf("Error receiving data.\n");
closesocket(sd);
WSACleanup();
exit(0);
}
printf("Data: %s", data);
return 0;
}
Używam komputera z systemem Windows 7. Używam kodu Java w Eclipse. Kompiluję kod C z MinGW za pomocą polecenia:
gcc a.c -lws2_32
(„a.c” to nazwa pliku).
Podczas gdy kod Java jest ważniejszy, z przyjemnością dowiem się, gdzie się mylę w jednym z moich przykładów kodu. Wszelkie sugestie są bardzo mile widziane.