views:

88

answers:

2

I have to connect to a remote server via UDP and send a predetermined message to it in order to get a message back. I had first tried this in TCP and it worked but in UDP after I send the message and listen for the reply in recvfrom() I get nothing. Can anyone tell me what might be the problem here.

if ((bytes_sent = sendto(sockfd, UDP_MSG, strlen(UDP_MSG), 0, p->ai_addr, p->ai_addrlen)) == -1) {
            perror("ClientUDP: Error sending data");
            exit(1);
        }

printf("Data sent %s\n", UDP_MSG);  

len = sizeof(struct sockaddr_storage);

if ((bytes_recv = recvfrom(sockfd, bufudp, MAXDATASIZE-1, 0,(struct sockaddr*)&addr, &len)) == -1) {
            perror("Error receiving in UDP");
            exit(1);
        }



printf("Bytes recv %d\n", bytes_recv);  

bufudp[bytes_recv] = '\0';
printf("ClientUDP: Received\n %s \n",bufudp );   

The port is entered from the keyboard using scanf() and the message is the string "HI".

A: 

TCP and UDP are not interchangeable. Some specific protocols use both (DNS for example), but bulk of them pick one or the other. HTTP(S) is built on top of TCP since is requires a bi-direction stream. Many audio/video protocols are built on top of UDP since missed/re-ordered packets (once in a while) are not critical.

In short, your server is probably only listening on TCP port, and not on UDP.

If you know that server is listening on both TCP and UDP, check the firewalls on both machines and along the route.

Nikolai N Fetissov
well everything is supposed to be working and there is no issue with the firewall. the thing is only if i send the exact message on the given port number will i receive any msg from the server. is there any other thing that might go wrong like msg buffers or anything??
sfactor
Yes, with UDP many things might go wrong - since there's no guarantee in the UDP itself - any node on the route, including source and destination, might just drop the datagram; the server socket receive buffer might be full (again, the result is dropped datagram). But it looks like your problem is most likely in the wrong format of the message. Is the server an embedded system (like those small wireless routers) by any chance? Then it might be of different *endianness*. You really have to study the application protocol to figure out what's wrong there.
Nikolai N Fetissov
A: 

If you want to see whether the UDP packet is leaving your machine with the correct contents and addresses you expect I'd install Wireshark. This utility will capture and decode all IP packets sent/received by your computer.

One question, does recvfrom() return immediately or does it just block? If it returns immediately I'd check to see if the return value is -1, if so that indicates an error code is present in errno.

Andrew O'Reilly
yeah i'll check using wireshark, thanx for the suggestion. in regards to your question it basically it just blocks.
sfactor