write() / read() syntax

hi

am newbie to unix and socket programing

I am trying to figuring out syntax for read and write

to send data from server to client and client can read it

I have to send two integers

write(newsockfd,buffer,"%d %d",x,y,0) 

writing from client where x and y are two integers..

read(sockfd,buffer,"%d %d",x,y,0); 

//reading them at client end

but am getting badaddress when reading them

can anyone help me out plz :slight_smile:

  1. use send() & recv() on sockets they are meant for that and return more meaningfull error codes.

  2. the syntax for write does not include a format string like:"%d %d" - the same is true for read
    example:

retval=write(newsockfd, buffer, number_bytes_to_write);
retval=read (newsockfd, buffer, number_bytes_to_read);
retval=send(sockfd, buffer, bufferlen, 0);
retval=recv(newsockfd, buffer, bufferlen, 0);

You code cannot have compiled at all. Always check the return code from system calls. The 0 (flags argument) for recv lets you do neat stuff like MSG_PEEK.

am checking error codes

its returning error reading from socket :bad address

on the server side error writing to socket:bad address

how can I send 2 different integers , where buffer is a char type ?

The send buffer is an address to memory of any type. send() doesn't really care whether you feed it a pointer to a string or an integer or structure or anything else, memory's memory as far as it's concerned. It just dumps it to the socket raw. Which means you need to order it the way your receiver expects yourself before you call send() at all.

Are you trying to send ASCII text, or binary data? If you want to send it as ASCII text, you'll need to convert it:

char buf[128];
int len=sprintf(buf, "%d %d", val1, val2);
send(sock, buf, len, 0);

If you want to send it as raw binary, that's simple too:

int val1, val2;
int val1_net=htonl(val1), val2_net=htonl(val2);

send(sock, &val1_net, sizeof(val1_net), 0);
send(sock, &val2_net, sizeof(val2_net), 0);

i thik it should be

int len=sprintf(buf,"%d %d", val1, val2); 
send(sock, buf, len, 0);

You're right, my mistake.

But I don't understand

if i use send() and recv() its sending some garbage

i have used the aove syntax for both

but if i use write and read() I am getting correct output ????

Can you show your whole program please?