Advertisement
Guest User

Untitled

a guest
Nov 20th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 KB | None | 0 0
  1. #include <iostream>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <sys/socket.h>
  5. #include <sys/types.h>
  6. #include <netinet/in.h>
  7. #include <arpa/inet.h>
  8. #include <unistd.h>
  9. using namespace std;
  10.  
  11.  
  12. int main(){
  13.     const int port = 4444;
  14.  
  15.     int sockfd;
  16.     struct sockaddr_in serverAddr;
  17.  
  18.     int newSocket;
  19.     struct sockaddr_in newAddr;
  20.  
  21.     socklen_t addr_size;
  22.     char buffer[1024];
  23.  
  24.     sockfd = socket(AF_INET, SOCK_STREAM, 0);
  25.     if(sockfd == -1){
  26.         cerr<<"Socket fallita";
  27.         exit(1);
  28.     }
  29.     cout<<"[+]Server Socket Creata.\n";
  30.     memset(&serverAddr, '\0', sizeof(serverAddr));
  31.  
  32.     serverAddr.sin_family = AF_INET;
  33.     serverAddr.sin_port = htons(port);
  34.     serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
  35.  
  36.    
  37.     if((bind(sockfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr))) == -1){
  38.         cerr<<"Bind fallita";
  39.         exit(1);
  40.     }
  41.     cout<<"[+]Bind sulla Port numero "<<port<<endl;
  42.  
  43.  
  44.     if((listen(sockfd, 5)) == -1){
  45.         cerr<<"Listen fallita";
  46.         exit(1);
  47.     }
  48.     cout<<"[+]Sto ascoltanto...\n";
  49.  
  50.     newSocket = accept(sockfd, (struct sockaddr*)&newAddr, &addr_size);
  51.     if(newSocket == -1){
  52.         cerr<<"Accettazione fallita";
  53.         exit(1);
  54.     }
  55.     cout<<"Connessione accetta";
  56.  
  57.     strcpy(buffer, "Ciao, sono il server");
  58.     send(newSocket, buffer, strlen(buffer), 0);
  59.     cout<<"[+]Sto chiudendo la connessione\n";
  60.     close(sockfd);
  61.     close(newSocket);
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement