0
votes

I have received data from UDP socket fd. How can I use this information to establish a TCP connection from the sender. buf contains the TCP port.

struct sockaddr_storage remote_addr;
socklen_t remote_addr_len;

recvfrom(fd, buf, BUFSIZE, 0, (struct sockaddr *)&remote_addr, &remote_addr_len);

The code below is my attempt, but it doesn't work. I am new to socket programming and I am tearing my hair over trying to figure this out.

newfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
struct hostent *info;
info = gethostbyname(remoteAddr.h_addr);

struct sockaddr_in newConn;
newConn.sin_family = AF_INET;
bcopy((char *)info->h_addr, (char *)&newConn.sin_addr.s_addr, info->h_length);
newConn.sin_port = htons(mesgTcpPort); //mesgTcpPort is of type int gotten from buf


connect(newfd,(struct sockaddr *)&newConn,sizeof newConn);

Error checking is omitted.

1
If you add error checking, what errors do you get? (If you didn't get any, your code would be working.)Greg Hewgill
I have error checking in the actual code, I just removed it here to keep the code short.user1205604

1 Answers

0
votes

You shouldn't need gethostbyname, since the UDP packet contains an IP address, not a name, in its header (and given to you by recvfrom).

However, this approach has limited applicability, since the new connection won't traverse NAT because it won't be associated with the original UDP connection, since the protocol and port differ.