Not getting the exact data at server sent from client [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am writing a client / server system in which the client sends a record from client to server. I am trying to represent the data as a struct, but I do not successfully recv() the struct at the server end.
Here is my code:
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
#pragma pack(1)
struct emp
{
int id;
char *name;
} emp1, emp3;
#pragma pack(0)
int main(int argc, char *argv[])
{
int sockfd = 0, n = 0;
char recvBuff[1024];
struct sockaddr_in serv_addr;
memset(recvBuff, '0', sizeof(recvBuff));
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Error : Could not create socket \n");
return 1;
}
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(5000);
serv_addr.sin_addr = inet_addr("192.168.0.105");
if (inet_pton(AF_INET, argv[1], &serv_addr.sin_addr) <= 0)
{
printf("\n inet_pton error occured\n");
return 1;
}
if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\n Error : Connect Failed \n");
return 1;
}
emp1 = (struct emp *) malloc(sizeof(struct emp));
emp1.name = (char *) malloc((size)*(sizeof(char)));
printf("Enter name of employee : ");
scanf(" %[^\n]s", emp1.name);
printf("Enter emp id : ");
scanf(" %d", &emp1.id);
unsigned char *data = (unsigned char*) malloc(sizeof(regn));
memcpy(data, &regn, sizeof(regn));
sendto(sockfd, data, sizeof(emp1), 0, (SOCKADDR *) &serv_addr,
sizeof(serv_addr));
close(sockfd);
}
and my server is like this
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
struct emp
{
int id;
char *name;
} emp1, emp3;
int main(int argc, char *argv[])
{
int listenfd = 0, connfd = 0;
struct sockaddr_in serv_addr;
FILE *fp, *fp1;
char recvBuf[1025];
listenfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&serv_addr, '0', sizeof(serv_addr));
memset(sendBuff, '0', sizeof(sendBuff));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(5000);
bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
listen(listenfd, 10);
connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);
if(recvfrom(sd, recvBuf, recvBufSize, 0,
(struct sockaddr *) &clientAddr, &len) < 0)
{
printf("Error receiving message from client\n");
}
else
{
printf("Message received:%s\n", recvBuf);
printf("Size :%d\n", strlen(recvBuf));
memcpy(&emp1, recvBuf, sizeof(emp));
printf("name:%s\n", emp1.name );
printf("is:%d\n", emp1.id);
}

you are sending a struct which contains an integer and a char pointer. This pointer points to a completly random location, on the receiving system.
You have to send the content name points to.
You could send every member of the struct on its own. For members with variable length, you have to send the size first and allocate it on the receiving end.
As stated by John Bollinger: One of your structs is packed, the other not. this may cause additional problems with layout and size of the struct and is probably unnecessary .

Added this answer to answer to specific questions of the OP (it may seem a bit off track of the original question).
An example of simple streaming. It is simple because in a real streaming scenario you need object id's to be able to instantiate and load the real classes. But if you know already what class you are sending or receiving, their is no need for this complexity. If you are sending multiple instances of classes then you need a more complex streaming mechanism. As microsoft did for instance in MFC, Borland in OWL, .NET also has mechanisms in place, ...
namespace OMCIPoco{
typedef std::vector<unsigned char> ucharvector;
SystemData::stream& operator <<(SystemData::stream& stream,const ucharvector& data);
SystemData::stream& operator >>(SystemData::stream& stream,ucharvector& data);
}
The cpp file :
SystemData::stream& operator <<(SystemData::stream& stream,const ucharvector& data)
{
stream << (unsigned long)data.size();
for (ucharvector::const_iterator it=data.begin();it<data.end();++it)
stream << *it;
return stream;
}
SystemData::stream& operator >>(SystemData::stream& stream,ucharvector& data)
{
unsigned long count;
stream >> count;
data.reserve(count);
for (unsigned int i=0;i<count;++i){
unsigned char c;
stream >> c;
data.push_back(c);
}
return stream;
}
Notice how the << and >> are in balance.
The stream is an interface that makes abstraction of the medium you are streaming to, it can be memory or disk or a networkstream. I can solve little endian problems using the streaming concept here as well, because the stream knows how to (de)serialise shorts, longs, ..., and it knows howto buffer as well.
You can use a flat structure as well avoiding the above complexity completely
class data{
public:
char name[20];
};
now using sizeof(data) will be correct because you will send the entire data struct. I used class here but struct works just the same way. The downside is that if the name contains only 10 charakters you will still send 20.

Related

Invalid Argument from sendto() Socket Program in C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm trying to make a simple client-server API to be used for two of my machines. I made this simple program that uses the functions I made to test it. For some reason my client sends a message just fine, but my server can't (however, it receives the message from the client).
Server side output:
host name: my_host
Our port number is: 34440
Client msg: Client msg
Send failed: Invalid argument
Message from Server sent to Client
Client side output:
Connection established with server...
Message from Client sent to Server
Server side:
#include <sys/socket.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdlib.h>
#include "my_socket.h"
int main() {
server_init();
char *msg = "Server msg";
char buffer[100];
int n = read_from_client((char *)buffer);
buffer[n] = '\0';
printf("Client msg: %s\n", buffer);
write_to_client((char *)msg);
printf("Message from Server sent to Client \n");
return 0;
}
Client Side:
#include <sys/socket.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdlib.h>
#include "my_socket.h"
int main() {
client_init();
char *msg = "Client msg";
char buffer[100];
write_to_server((char*)msg);
printf("Message from Client sent to Server \n");
int n = read_from_server((char *)buffer);
buffer[n] = '\0';
printf("Server msg: %s\n", buffer);
close_socket();
return 0;
}
my_socket.c:
#include "my_socket.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
int sockfd1;
int sockfd2;
int MAX_BUFF = 1024;
struct sockaddr_in server;
struct sockaddr_in client;
struct hostent *host;
ssize_t write_to_server(const void *buffer){
int bytes_sent, server_size = sizeof(server), buf_len = strlen(buffer);
if ((bytes_sent = sendto(sockfd2, buffer, buf_len, 0,
(const struct sockaddr *)&server, server_size)) < 0){
perror("Send failed");
}
return bytes_sent;
}
ssize_t write_to_client(const void *buffer){
int bytes_sent, client_size = sizeof(client), buf_len = strlen(buffer);
if ((bytes_sent = sendto(sockfd1, buffer, buf_len, 0,
(const struct sockaddr *)&client, client_size)) < 0){
perror("Send failed");
}
return bytes_sent;
}
int read_from_server(void *buffer){
int bytes_rcv, len;
if ((bytes_rcv = recvfrom(sockfd2, buffer, MAX_BUFF, MSG_WAITALL,
(struct sockaddr *)&server, &len)) < 0){
perror("Read failed");
}
return bytes_rcv;
}
int read_from_client(void *buffer){
int bytes_rcv, len;
if ((bytes_rcv = recvfrom(sockfd1, buffer, MAX_BUFF, MSG_WAITALL,
(struct sockaddr *)&client, &len)) < 0){
perror("Read failed");
}
return bytes_rcv;
}
void close_socket() {
close(sockfd1);
close(sockfd2);
}
void server_init(){
if ( (sockfd1 = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
perror("socket creation failed");
}
char name[1024];
name[1023] = '\0';
gethostname(name, 1023);
printf("host name: %s \n", name);
host = gethostbyname("my_host");
if(host == NULL){
perror("Host is null");
exit(0);
}
bzero((char *)&server, sizeof(server));
bzero((char *)&client, sizeof(client));
server.sin_family = AF_INET;
bcopy((char *)host->h_addr,
(char *)&server.sin_addr.s_addr, host->h_length);
//server.sin_port = 0;
server.sin_port = htons(34440);
if ( (bind(sockfd1, (struct sockaddr *)&server, sizeof(server) ) ) < 0 ){
perror("bind failed");
}
socklen_t len = sizeof(server);
if (getsockname(sockfd1, (struct sockaddr *)&server, &len) == -1){
perror("getsockname");
}else{
printf("Our port number is: %d\n", ntohs(server.sin_port));
}
}
void client_init(){
if ( (sockfd2 = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
perror("socket creation failed");
}
host = gethostbyname("my_host");
if(host == NULL){
perror("Host is null");
exit(0);
}
bzero((char *)&server, sizeof(server));
server.sin_family = AF_INET;
bcopy((char *)host->h_addr,
(char *)&server.sin_addr.s_addr, host->h_length);
//server.sin_port = 0;
server.sin_port = htons(34440);
if(connect(sockfd2, (struct sockaddr *)&server, sizeof(server)) == 0){
printf("Connection established with server...\n");
}
}
my_socket.h:
#ifndef MY_SOCKET
#define MY_SOCKET
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
extern int sockfd1;
extern int sockfd2;
extern int MAX_BUFF;
extern struct sockaddr_in server;
extern struct sockaddr_in client;
extern struct hostent *host;
// Send a message over the socket
ssize_t write_to_server(const void *buffer);
ssize_t write_to_client(const void *buffer);
// Blocks until told it's ready; receives bytes from socket
int read_from_server(void *buffer);
int read_from_client(void *buffer);
// Close the socket
void close_socket();
void server_init();
void client_init();
#endif
Any advice or criticism is welcome. Thanks in advance.
At least one issue is that you are not initializing the len variable in read_from_client. The manual page for recvfrom says, in part (emphasis added):
... addrlen is a value-result argument. Before the call, it should be initialized to the size of the buffer associated with src_addr. Upon return, addrlen is updated to contain the actual size of the source address. The returned address is truncated if the buffer provided is too small; in this case, addrlen will return a value greater than was supplied to the call.
That means that, as an uninitialized stack variable, len has an indeterminate value. Probably zero, but at least something smaller than sizeof(struct sockaddr_in). As a result, client is not getting filled in correctly by the recvfrom.
Just before the recvfrom, you should initialize it with:
len = sizeof(client);
On the client side, write_to_server and read_from_server need not use recvfrom and sendto as you have already done a connect on the socket. They can simply use recv and send since the remote socket endpoint is already established by the connect. I believe the address is simply ignored for a connected socket, but I cannot find where that is documented right now.
(In any case, if you do continue to use recvfrom on the client side, you should make the same len initialization there.)

sending message from client to server and vice versa

I have the following code for client and server
#include <sys/types.h>
#include <netinet/in.h>
#include <inttypes.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <strings.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int socket_fd;
struct sockaddr_in dest;
struct hostent *hostptr;
struct { char head; u_long body; char tail; } msgbuf;
socket_fd = socket (AF_INET, SOCK_DGRAM, 0);
bzero((char *) &dest, sizeof(dest)); /* They say you must do this */
hostptr = gethostbyname(argv[1]);
dest.sin_family = (short) AF_INET;
bcopy(hostptr->h_addr, (char *)&dest.sin_addr,hostptr->h_length);
dest.sin_port = htons((u_short)0x3333);
msgbuf.head = '<';
msgbuf.body = htonl(getpid()); /* IMPORTANT! */
msgbuf.tail = '>';
sendto(socket_fd,&msgbuf,sizeof(msgbuf),0,(struct sockaddr *)&dest,
sizeof(dest));
return 0;
}
server:
#include <sys/types.h>
#include <netinet/in.h>
#include <inttypes.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <strings.h>
#include <unistd.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
int socket_fd, cc, fsize;
struct sockaddr_in s_in, from;
struct { char head; u_long body; char tail;} msg;
socket_fd = socket (AF_INET, SOCK_DGRAM, 0);
bzero((char *) &s_in, sizeof(s_in)); /* They say you must do this */
s_in.sin_family = (short)AF_INET;
s_in.sin_addr.s_addr = htonl(INADDR_ANY); /* WILDCARD */
s_in.sin_port = htons((u_short)0x3333);
printsin( &s_in, "RECV_UDP", "Local socket is:");
fflush(stdout);
bind(socket_fd, (struct sockaddr *)&s_in, sizeof(s_in));
for(;;) {
fsize = sizeof(from);
cc = recvfrom(socket_fd,&msg,sizeof(msg),0,(struct sockaddr *)&from,&fsize);
//printsin( &from, "recv_udp: ", "Packet from:");
printf("Got data ::%c%ld%c\n",msg.head,(long) ntohl(msg.body),msg.tail);
fflush(stdout);
}
return 0;
}
I'm looking for a way to change this code so that:
1.The client will send my name to the server and then will receive the server response.
2.On the server side, the server will receive the client name (instead of the current msg structure) and will send back its name.
I'm assuming I should just put my name in the msgbuf.body like this
msgbuf.head = '<';
msgbuf.body = 'liana';
msgbuf.tail = '>';
and delete the
msgbuf.body = htonl(getpid()); line.
or maybe make a new string for my name like this string name="liana";
and put it in the msgbuf.body like this msgbuf.body=name;(???)
is this the right deriction?
for reciving the response of the server I assume it is the same way as it was done for the server
should I add to client something like this?
int socket_fd, cc, fsize; // the socket that we receive to
struct sockaddr_in s_in, from; // decleration of the server and sending
(to the server) struct
fflush(stdout);//to ensure that whatever you just wrote to a file/the console is indeed written out on disk/the console.
bind(socket_fd, (struct sockaddr *)&s_in, sizeof(s_in));// conecting
between
the socket and all the details we entered
for(;;) {//infinite loop
fsize = sizeof(from);//set the size of the socket we resive to
cc = recvfrom(socket_fd,&msg,sizeof(msg),0,(struct sockaddr
*)&from,&fsize);//recive massage using UDP protocol
printf("Got data ::%c%ld%c\n",msg.head,(long) ntohl(msg.body),msg.tail);
//print the whole massage
fflush(stdout);//to ensure that whatever you just wrote to a file/the
console is indeed written out on disk/the console.
}
and just leave it like this without changing anything?
**how can I make the server receive the my name (instead of the current msg
structure)and send it back?
should I send it back using the
sendto(socket_fd,&msgbuf,sizeof(msgbuf),0,(struct sockaddr *)&dest,
sizeof(dest));
line?
**if I cant use the structure anymore how should i change this line?****
any help whould be appreciated,I'm kind of new to C and never worked with the client/server model

unexpected multithreaded server reaction - C

I'm working on a multithreaded server/client. The problem I have is that the server handling sometimes looks a little bit various. The message, which is send back is always correct, but the message the server prints out is a little bit weird. If it is a short word like "hello" everything works. If it is a long word or there are spaces in the string like "Binominalkoeffizient" the out-printed serversided message is:
Binomina
lkoeffiz
ient
fiz
Any idea where my mistake is?
PS: The server reaction is the same when I use telnet!
Server-Main:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>
#include "server.h"
int main(int argc, const char * argv[]) {
int sock;
struct sockaddr_in server;
sock = socket(AF_INET, SOCK_STREAM, 0);
socketStatusCheck(sock);
puts("[*] Starting Server ...");
puts("[*] Initialize Server ...");
initializeServer(&server, 8888);
bindServerToAddress(sock, server);
puts("[*] Waiting for incomming connections ... ");
puts("");
listen(sock, 3);
connectionSwitch(sock);
close(sock);
return 0;
}
Server-File
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>
#include "server.h"
void socketStatusCheck(int sock) {
if (sock == -1) {
perror("Error creating the socket: ");
exit(0);
}
}
void initializeServer(struct sockaddr_in *server, int port) {
server->sin_family = AF_INET;
server->sin_addr.s_addr = INADDR_ANY;
server->sin_port = htons(port);
}
void bindServerToAddress(int sock, struct sockaddr_in server) {
if (bind(sock, (struct sockaddr*) &server, sizeof(server)) < 0) {
perror("Error binding port: ");
}
}
void connectionSwitch(int sock) {
int nsock, lenbuf;
struct sockaddr_in client;
pthread_t pid = NULL;
lenbuf = sizeof(struct sockaddr_in);
while ((nsock = accept(sock, (struct sockaddr*) &client, (socklen_t*) &lenbuf))) {
puts("Client connected!");
if (pthread_create(&pid, NULL, connectionHandler, (void*) &nsock))
perror("Error creating thread: ");
}
if (nsock < 0) {
perror("Error accepting incomming client: ");
}
pthread_exit(pid);
}
void *connectionHandler(void *sockptr) {
int sock = *(int*) sockptr;
long isConnected;
char *smessage, *recvmessage;
smessage = "Hello! I am the server you just connected! \n";
write(sock, smessage, strlen(smessage));
recvmessage = malloc(5000 * sizeof(char)); // while ((isConnected = recv(sock, recvmessage, sizeof(recvmessage), 0)) > 0)
while ((isConnected = recv(sock, recvmessage, sizeof(recvmessage), 0)) > 0) {
//write(sock, recvmessage, sizeof(recvmessage));
send(sock, recvmessage, sizeof(recvmessage), 0);
puts(recvmessage);
}
if (isConnected == 0) {
perror("Client disconnected: ");
fflush(stdout);
}
free(recvmessage); recvmessage = NULL;
return 0;
}
This really has nothing to do with multithreading, and everything to do with the nature of SOCK_STREAM sockets.
Stream sockets are, as the name suggests, a stream of bytes; they do not preserve message boundaries such that what is sent with one call to send is received with one call to recv. A single send may be broken up across multiple recv calls, or multiple send calls may be coalesced into a single recv, or both. They do guarantee order, in that the bytes will be received in the same order they are sent.
You'll need to implement your own record marking, perhaps by inserting \0 characters to delimit words, or by using length prefixes.
This is normal behavior. When you use send you don't know how many bytes will be sent. It may happen that all the words , characters are sent.However there are ways to solve this problem. One way is to write a simple header to the string you send , which contains the length of the string you are sending . So you know when the string is ending . For example you can use a thread to look continuously for messages and because the header contains the length of the string you know when to print a \n.The behavior of the send cannot be altered , because it is the Kernel , that is doing this .
In addition to what the other answers say already:
Your code specifically asks to read 8 bytes at a time. recvmessage is a pointer, and pointers are 8 bytes on your system, so sizeof(recvmessage) is 8.

C concurrent UDP socket , weird segmentation fault

I'm either very tired and not noticing something simple , or this is completely screwing with me. I'm getting a segmentation fault ( core dumped ) and I've managed to pinpoint it to the sendto() in the worker function. (in the server)
Server code:
//UDPServer.c
/*
* gcc -o server UDPServer.c
* ./server <port> <buffersize>
*/
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
void err(char *str)
{
perror(str);
exit(1);
}
int sock;
typedef struct
{
struct sockaddr_in client;
int buffsize;
char *msg;
} data;
void *worker (void* asd)
{
int len;
FILE *fp;
data d;
d = *(data*) asd;
char buff[d.buffsize];
printf("Received packet from %s:%d\nData:%sSize:%d\n",
inet_ntoa(d.client.sin_addr), ntohs(d.client.sin_port)
,d.msg,d.buffsize);
char * fn;
memcpy (fn,d.msg,strlen(d.msg)-1);
fp = fopen(fn,"rb");
int bytes;
len = sizeof(d.client);
printf ("%d\n",len);
while (bytes=fread(buff,sizeof(char),d.buffsize,fp))
{
printf ("Server sent %d bytes.\n",bytes);
-> this if right here. this causes the core dump when attempting to send
if(sendto(sock , &buff , sizeof(buff),0,(struct sockaddr *)&d.client,len)<0)
err("Error sending.");
}
fclose(fp);
}
int main(int argc, char** argv)
{
struct sockaddr_in server, client;
int port, i;
socklen_t slen=sizeof(client);
if(argc != 3)
{
printf("Usage: <Port> <Bytes>\n");
exit(0);
}
else
sscanf(argv[1],"%d",&port);
int buffsize = atoi(argv[2]);
char buff[buffsize];
if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
err("socket");
else
printf("Server : Socket() successful\n");
bzero(&server, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sock, (struct sockaddr* ) &server, sizeof(server))==-1)
err("bind");
else
printf("Server : bind() successful\n");
while(1)
{
memset(&buff,0,sizeof(buff));
if (recvfrom(sock, &buff, sizeof(buff), 0, (struct sockaddr*)&client, &slen)==-1)
err("recvfrom()");
data d;
d.client = client;
d.buffsize = buffsize;
d.msg = buff;
pthread_t t;
pthread_create(&t,NULL,worker,&d);
pthread_join(t,NULL);
}
return 0;
}
I don't think the client is relevant here since it's only job is to send the filename. The read works btw , I've tested.
Anyway , I'm just trying to send the content of the file for the moment.I've been trying to figure this out for the past hour and for the life of me I can't find out what's it's problem. The segmentation fault makes no sense to me.
Any suggestions are greatly appreciated.
I'd be nervous about the sizeof(buff) in the sendto. buff's size is fixed at runtime based on the argument. But sizeof is a compile-time operation. (Or at least it was back in the good old days - I'm not sure about C99) Oh, nevermind - I see that has changed
Still, why not use d.buffsize there instead? Or maybe bytes, since you might not have filled the buffer.
Although #21Zoo is wrong about dynamic arrays in C99, I think he found the root problem
char * fn;
memcpy (fn,d.msg,strlen(d.msg)-1);
fn has no memory allocated to copy into, so you are writing to a random point in memory.
Something in the sendto is probably stumbling over that memory which now contains garbage.
You either need to malloc(strlen(d.msg)+1) or use strdup instead.

simple TCP client serve model in C : client not recieving

im making a simple TCP client-server in c and im trying to send a message from the client to the server, but im having some problems with it.
The server does send the message (integer value > 0) but the client is unable to receive it (integer value > 0)
here is the code:
Client
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <stdio.h>
int main()
{
int s_id;
char *msg = "hello";
struct sockaddr_in serv_addr;
s_id = socket (AF_INET, SOCK_STREAM, 0);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons (1156);
serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
connect(s_id,(struct sockaddr *) &serv_addr, sizeof (struct sockaddr));
int r = recv (s_id, (char *) msg, 9, 0);
printf("%d \n", r );
printf("%s \n", msg );
return 0;
}
Server:
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
int main()
{
int s_id;
char *msg = "connected";
struct sockaddr_in my_addr, remote_addr;
s_id = socket (PF_INET,SOCK_STREAM,0);
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(1156);
my_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
bind(s_id,(struct sockaddr *) &my_addr, sizeof(struct sockaddr));
listen (s_id,5);
int size = sizeof (struct sockaddr_in);
int new_sd = accept (s_id, (struct sockaddr *) &remote_addr, &size);
int s= send(new_sd, (void *)msg, 9, 0);
printf("%d \n", s );
return 0;
}
The outputs i get (after first starting the server, and then the client) are
server side: 9
client-side: -1
hello
I am using Ubuntu 11.04 and the gcc compiler.
I hope someone out there can help.
Thank you
Umar
char *msg = "hello";
This is a string literal. It's a constant, and you can't change it.
int r = recv (s_id, (char *) msg, 9, 0);
And there you're trying to write to it.
Change your declaration to:
char msg[20];
memset(msg, 0, sizeof(msg));
If you make that change, your code works as expected.
In C you're going to have to allocate and manage buffers - there's no free lunch :)
Also take note of the other answer from Nikolai N Fetissov - you really should be checking return codes from all the system calls.
You never check for errors after any of the system calls. All of socket(2), connect(2), etc. return -1 on failure, then you can print the error description with, say, perror(3) function. Each system call manual page lists possible errors.
Edit 0:
The real problem is probably what Brian points out - you are trying to receive data into read-only memory on the client. Does it die with a segfault?

Resources