I have write server and client programs for experiment. I want achieve that effect: once server transfer "HELLO", the client w receive it and send back "HELLO FROM WIN" and wait for the next information. However, the server only get the first response and the client crushed(shutdown a few seconds later), Some codes are below.
client.c
int main(int argc, char * argv[]){
char receive[6] = "";
char *send = "HELLO FROM WIN";
startupWSA();
SOCKET sock = createTCPSocket();
while(1){
recv(sock,receive,6,0);
printf("%s\n",payload);
printf("%s\n",receive);
memset(receive,'\0',6);
sendto(sock,send,16,0,(const struct sockaddr *)&addr,sizeof(addr));
memset(send,'\0',16);
}
}
server.py
from socket import *
serverPort = 5555
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('',serverPort))
serverSocket.listen(1)
print('socket is ready')
connectionSocket,addr = serverSocket.accept()
while True:
send = input('>')
connectionSocket.send(send.encode())
receive = connectionSocket.recv(1024).decode()
print(receive)
Anyone can help me? Thanks.
char *send = "HELLO FROM WIN";
That's a pointer to a read-only string literal. In C you are allowed to have a non-const pointer to it (until C11 I believe), but you still cannot write to it. You try to do this here:
memset(send,'\0',16);
This is undefined behavior so crashing is a definite possibility (and a good one, too - much better than "working" until you deploy your code to production!)
To get around it you can change send
to be an array with automatic storage:
char send[] = "HELLO FROM WIN";
And to make sure you don't write out of bounds:
sendto(sock,send,sizeof(send),0,(const struct sockaddr *)&addr,sizeof(addr));
memset(send, '\0', sizeof(send));