C Socket Programming #1
Sockets are the basic building block of network communication, so they are a good place to start. In this post we create a socket in C, use it to connect to a server, and then talk to that server through it: we send a message and copy the reply back into an array.
THE CODE IN THIS POST HAS BEEN TESTED ON LINUX DISTRIBUTIONS. WINDOWS USERS SHOULD CHANGE THE HEADERS IF THEY ENCOUNTER FUNCTIONS THAT DO NOT WORK.
We take our code from this link.
The first thing we need is the socket itself.
socket(AF_INET , SOCK_STREAM , 0);
Each argument here tells the socket how to behave. AF_INET indicates that we will use IPv4 (for IPv6 we can use AF_INET6 instead). SOCK_STREAM specifies which type the socket will use, and here that means TCP. The trailing 0 is added for the IP protocol.
server.sin_addr.s_addr = inet_addr("172.217.22.14");
server.sin_family = AF_INET;
server.sin_port = htons( 80 );
Next we need to describe where we are connecting to. We created a struct named server and have to pass into it the IP we are going to connect to. Since IPs need to be converted to the long type in sockets, we use the inet_addr function to copy it into the variable inside our struct.
In the same struct, after specifying that we will use the IPv4 family, we write our connection port. Here, too, we need to send the port through the htons function.
connect(socket_desc , (struct sockaddr *)&server , sizeof(server))
With everything described, the connect() function is what actually reaches out to the server we specified.
We pass it the socket we created, the struct we filled in for the server, and its size. If it returns a value less than 0, the connection could not be established.
send(socket_desc , message , strlen(message) , 0)
Now that the connection is up, we can send a message to the server.
For this, the send() function takes the socket we created, the message we want to send, and the size of that message. As with connect, a sending error here shows up as a returned value less than 0; if it is greater, the message was sent successfully.
recv(socket_desc, server_reply , 2000 , 0)
Once the message has gone out successfully, the last step is receiving the server’s reply.
The recv() function takes the socket we use and the size of the char variable where the reply will be written, and hands the reply back to us.
#include <stdio.h>
#include <string.h> //strlen
#include <sys/socket.h>
#include <arpa/inet.h> //inet_addr
int main(int argc , char *argv[])
{
int socket_desc;
struct sockaddr_in server;
char *message , server_reply[2000];
//Create socket
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
{
printf("Could not create socket");
}
server.sin_addr.s_addr = inet_addr("172.217.22.14");
server.sin_family = AF_INET;
server.sin_port = htons( 80 );
//Connect to remote server
if (connect(socket_desc , (struct sockaddr *)&server , sizeof(server)) < 0)
{
puts("connect error");
return 1;
}
puts("Connected\n");
//Send some data
message = "a";
if( send(socket_desc , message , strlen(message) , 0) < 0)
{
puts("Send failed");
return 1;
}
puts("Data Send\n");
//Receive a reply from the server
if( recv(socket_desc, server_reply , 2000 , 0) < 0)
{
puts("recv failed");
}
puts("Reply received\n");
puts(server_reply);
close(socket_desc);
return 0;
}
– Turkish Version –
C Socket Programlama #1
Soketler ağ iletişiminin temel yapı taşı olduğu için başlamak için iyi bir yer. Bu yazıda C kullanarak bir soket oluşturup bir servera bağlanıyoruz; bağlandığımız servera soket aracılığıyla iletişim kurarak mesaj gönderiyor ve cevabı bir diziye aktarıyoruz.
BU YAZIDAKI KODLAR LINUX DAĞITIMLARI İÇİN DENENMİŞTİR. WİNDOWS KULLANICILARI EĞER ÇALIŞMAYAN FONKSİYONLAR OLURSA HEADERLARI DEĞİŞTİRMELİDİR
Kodlarımızı bu linkten alıyoruz.
İhtiyacımız olan ilk şey soketin kendisi.
socket(AF_INET , SOCK_STREAM , 0);
Buradaki her parametre soketin nasıl davranacağını belirtiyor. AF_INET IPv4 kullanacağımızı belirtiyor (IPv6 için bunun yerine AF_INET6 kullanabiliriz). SOCK_STREAM ise soketin hangi tipi kullanacağını belirtiyor ve burada bu TCP demek. Sondaki 0 ise IP protokolü için eklendi.
server.sin_addr.s_addr = inet_addr("172.217.22.14");
server.sin_family = AF_INET;
server.sin_port = htons( 80 );
Sırada nereye bağlanacağımızı tarif etmek var. server adında bir struct oluşturduk ve bunun içerisine bağlanacağımız IP’yi aktarmamız gerekiyor. Soketlerde IP’lerin long tipine dönüştürülmesi gerektiği için inet_addr fonksiyonunu kullanarak struct içindeki değişkenimize aktarıyoruz.
Yine aynı struct içerisinde IPv4 ailesini kullanacağımızı belirttikten sonra bağlantı portumuzu yazıyoruz. Burada da portu htons fonksiyonu ile göndermemiz gerekiyor.
connect(socket_desc , (struct sockaddr *)&server , sizeof(server))
Her şeyi tarif ettikten sonra belirlediğimiz servera asıl ulaşan şey connect() fonksiyonu oluyor.
İlk olarak oluşturduğumuz soketi, server için doldurduğumuz struct yapısını ve bunun boyutunu parametre olarak gönderiyoruz. Eğer 0’dan küçük bir değer üretirse bağlantı sağlanamamıştır.
send(socket_desc , message , strlen(message) , 0)
Artık bağlantı kurulduğuna göre servera mesaj gönderebiliriz.
Bunun için send() fonksiyonu oluşturduğumuz soketi, göndermek istediğimiz mesajı ve bu mesajın boyutunu alıyor. Yine connect fonksiyonunda olduğu gibi burada da gönderim hatası olursa gelen değer 0’dan küçük olacaktır; eğer büyükse mesaj başarıyla iletilmiştir.
recv(socket_desc, server_reply , 2000 , 0)
Mesaj başarıyla gittikten sonra son adım serverın cevabını almak.
recv() fonksiyonu kullandığımız soketi ve cevabın yazılacağı char değişkeninin boyutunu alarak bize cevabı iletir.
#include <stdio.h>
#include <string.h> //strlen
#include <sys/socket.h>
#include <arpa/inet.h> //inet_addr
int main(int argc , char *argv[])
{
int socket_desc;
struct sockaddr_in server;
char *message , server_reply[2000];
//Create socket
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
{
printf("Could not create socket");
}
server.sin_addr.s_addr = inet_addr("172.217.22.14");
server.sin_family = AF_INET;
server.sin_port = htons( 80 );
//Connect to remote server
if (connect(socket_desc , (struct sockaddr *)&server , sizeof(server)) < 0)
{
puts("connect error");
return 1;
}
puts("Connected\n");
//Send some data
message = "a";
if( send(socket_desc , message , strlen(message) , 0) < 0)
{
puts("Send failed");
return 1;
}
puts("Data Send\n");
//Receive a reply from the server
if( recv(socket_desc, server_reply , 2000 , 0) < 0)
{
puts("recv failed");
}
puts("Reply received\n");
puts(server_reply);
close(socket_desc);
return 0;
}