Reputation: 817
I have written this program:
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int socket_desc;
struct sockaddr_in adress;
int addrlen;
int new_socket;
int bufsize = 1024;
char *you_sent = "You sent: ";
int main() {
char *buffer = malloc(bufsize);
socket_desc = socket(AF_INET, SOCK_STREAM, 0);
adress.sin_family = AF_INET;
adress.sin_addr.s_addr = INADDR_ANY;
adress.sin_port = htons(7000);
bind(socket_desc, (struct sockaddr *)&adress, sizeof(adress));
listen(socket_desc, 3);
addrlen = sizeof(struct sockaddr_in);
new_socket = accept(socket_desc, (struct sockaddr *)&adress, &addrlen);
while(recv(new_socket,buffer,bufsize,0))
{
printf("I recieved: %s", buffer);
send(new_socket, you_sent, strlen(you_sent), 0);
send(new_socket, buffer, strlen(buffer), 0);
memset(buffer, '\0', sizeof(buffer));
}
}
I can connect to the server with a telnet. And write stuff to the application and recieve data from the application. But i cannot get my head around how i can connect to this with another c program and send and recieve data from that program. I have tried this:
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int socket_desc;
struct sockaddr_in adress;
int addrlen;
int new_socket;
char *message_to_send = "Hello world!";
int main() {
socket_desc = socket(AF_INET, SOCK_STREAM, 0);
adress.sin_family = AF_INET;
adress.sin_addr.s_addr = INADDR_ANY;
adress.sin_port = htons(7000);
bind(socket_desc, (struct sockaddr *)&adress, sizeof(adress));
listen(socket_desc, 3);
addrlen = sizeof(struct sockaddr_in);
new_socket = accept(socket_desc, (struct sockaddr *)&adress, &addrlen);
send(new_socket, message_to_send, strlen(message_to_send), 0);
}
Upvotes: 1
Views: 2228
Reputation: 14078
The sequence is the following:
Server side:
socket
syscall;bind
syscall;listen
syscall (this will enable the backlog queue);accept
syscall
accept
function will return a new file descriptor representing the new connection. You will use this one to send/receive data with the other host, while the original file descriptor (from socket
) will be used for new incoming connections.Client side:
socket
;connect
.Here you may find some additional resources.
Upvotes: 4
Reputation: 59997
A server is like a telephone operator on a switch board. That person does the following:
bind
to a number)listen
)accept
)The person at the other end just wants to make a call to that person. (i.e. connect
). The person only needs to go to the phone when a call needs to be made. Therefore not bound to the phone or has to listen for it to ring.
I hope this metaphor helps in your understanding.
PS: The socket
part is the phone socket on the wall.
Upvotes: 5