Reputation:
I got trouble on using sendto()
function in socket
int main(int argc, const char * argv[]) {
int acceptFd;
struct sockaddr_in servaddr, cliaddr;
char recieveBuf[512];
char sendBuf[512];
socklen_t cliLen;
if(-1 == (acceptFd = socket(AF_INET,SOCK_DGRAM,0))) perror("socket() failed.\n");
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(6789);
if(-1==bind(acceptFd,(struct sockaddr*)&servaddr,sizeof(servaddr))) perror("bind() failed.\n");
bzero(&cliaddr, sizeof(cliaddr));
while(1){
if(recvfrom(acceptFd, recieveBuf, 512, 0, (struct sockaddr*) &cliaddr, &cliLen) == -1) {
perror("recvfrom() failed");
continue;
}
strcpy(sendBuf,"recieved\n");
printf("%s\n",sendBuf);
if(-1 == sendto(acceptFd,sendBuf, 512,0,(struct sockaddr*)&cliaddr,cliLen)){
perror("sendto() failed");
continue;
}
}
}
the recvfrom()
works fine, but every time sendto()
was called, the error handling print out this: sendto() failed: Invalid argument
the send program is here:
#include "test.AcceptMessage.pb.h"
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
int main(int argc, const char * argv[]) {
int sendSocket;
struct sockaddr_in cliaddr;
char buf[512];
if(-1 == (sendSocket = socket(AF_INET,SOCK_DGRAM,0))) perror("socket() failed.\n");
bzero(&cliaddr, sizeof(cliaddr));
cliaddr.sin_family = AF_INET;
cliaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
cliaddr.sin_port = htons(6789);
sendto(sendSocket,buf, 512,0,(
struct sockaddr*)&cliaddr, sizeof(cliaddr));
recvfrom(sendSocket,buf,512,0, nullptr, nullptr);
printf("%s\n",buf);
return 0;
}
So what's wrong with this code?
Upvotes: 1
Views: 2290
Reputation: 310903
You don't have any reason to use recvfrom()
and sendto()
at all here. It's a connected socket. Just use send()
and recv().
Upvotes: 0
Reputation: 15229
From man recvfrom
:
Before the call, it [addrlen] should be initialized to the size of the buffer associated with src_addr.
Therefore, initialize your cliLen
variable with:
socklen_t cliLen = sizeof(cliaddr);
Upvotes: 3