AdSense

Sunday, 29 September 2013

Raspberry PI - C++ - Open socket

(Deutsche Version) Today, I want to show how to open a socket in C++. The reason for this post is: I have a Raspberry PI who does lot of things like reading temperature, controlling several things in the house. Handling the communication to the Raspberry PI via files is not a good solution, so I want to communicate directly vie network with the Raspberry PI. Therefore, the Raspberry PI has to open a network socket. I copied the code from other sources and adapted it a bit. I only need the receiving and the sending of messages. I also defined the message length to 256 bytes. The code for opening a socket is the following:

//define variables 
int sockfd, newsockfd, portno = 82; //number of port
socklen_t clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n; 
 
//create socket 
sockfd = socket(AF_INET, SOCK_STREAM, 0);

bzero((char *) &serv_addr, sizeof(serv_addr));

serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);

bind(sockfd, (struct sockaddr *) &serv_addr,
        sizeof(serv_addr));
listen(sockfd,5);
clilen = sizeof(cli_addr); 
 
//accept tcp clients 
while(true)
{
  //accept client 
  newsockfd = accept(sockfd, 
            (struct sockaddr *) &cli_addr, 
            &clilen); 
  bzero(buffer,256);
  //read client message into buffer
  n = read(newsockfd,buffer,256);
  //write message to client
  n = write(newsockfd,"I got your message, this should be 256 bytes long",256);

  close(newsockfd);
}
close(sockfd);

No comments:

Post a Comment