#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main()
{
struct sockaddr_in addr;
int fd, cnt,ret;
char ch = 'y',msg[] ="How are you";
if ((fd=socket(AF_INET,SOCK_DGRAM,0)) < 0) {
printf("Error: socket");
exit(1);
}
printf("\nDone socket\n");
/* set up destination address */
memset(&addr,0,sizeof(addr));
addr.sin_family=AF_INET;
addr.sin_addr.s_addr=inet_addr("128.88.143.113");
addr.sin_port=htons(9090);
ret=connect(fd,(struct sockaddr *)&addr,sizeof(addr));
perror("Connect:");
while(ch == 'y'){
cnt = send(fd,msg,sizeof(msg),0);
if(cnt < 0)
perror("send:");
printf("\nNumber of bytes sent = %d , \n",cnt);
printf("Continue (y/n)\n");
scanf(" %c",&ch);
}
return 0;
}
The above code is compiled to run on a Linux machine.
Assume that the above code sends data to a machine at IP address 128.88.143.113
. No UDP socket is bound to port 9090
at 128.88.143.113
.
In the while
loop, the first call to send()
succeeds(the packet actually goes out on the wire; checked it using trace
) and the second send()
fails with Connection refused
. The third send()
succeeds and the forth fails and so on.
I suspect that after first send()
the stack receives an ICMP error message(seen in tcpdump
on the Linux machine) which is saved in the socket structure. The second send()
fails upon seeing this error and no packet is actually sent out. The second send()
also clears the error in the socket structure. Therefore the third send()
succeeds and the forth fails and so on.
Questions:
- Is this assumption correct?
- What should be the correct behavior? Is there any RFC standard defining such behavior?
- Since UDP does not maintain any connection state, shouldn't every
send()
succeed?