0% found this document useful (0 votes)
11 views2 pages

PGM 1

Uploaded by

shekharblr2025
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views2 pages

PGM 1

Uploaded by

shekharblr2025
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

1 #include <stdio.

h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <sys/socket.h>
5 #include <netinet/in.h>
6 #include <unistd.h>
7
8 #define PORT 8080
9 #define MAX_CONNECTIONS 5
10 #define BUFFER_SIZE 1024
11
12 int main() {
13 int server_fd, new_socket, valread;
14 struct sockaddr_in address;
15 int addrlen = sizeof(address);
16 char buffer[BUFFER_SIZE] = {0};
17 char *hello = "Hello from server";
18
19 // 1. Create socket file descriptor
20 if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
21 perror("socket failed");
22 exit(EXIT_FAILURE);
23 }
24
25 // Optional: Set socket options to reuse address and port
26 int opt = 1;
27 if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt,
sizeof(opt))) {
28 perror("setsockopt");
29 exit(EXIT_FAILURE);
30 }
31
32 // 2. Prepare the server address structure
33 address.sin_family = AF_INET;
34 address.sin_addr.s_addr = INADDR_ANY; // Listen on all available interfaces
35 address.sin_port = htons(PORT);
36
37 // 3. Bind the socket to the specified IP and port
38 if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
39 perror("bind failed");
40 exit(EXIT_FAILURE);
41 }
42
43 // 4. Listen for incoming connections
44 if (listen(server_fd, MAX_CONNECTIONS) < 0) {
45 perror("listen");
46 exit(EXIT_FAILURE);
47 }
48
49 printf("Server listening on port %d\n", PORT);
50
51 // 5. Accept client connections in a loop
52 while (1) {
53 if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t
*)&addrlen)) < 0) {
54 perror("accept");
55 exit(EXIT_FAILURE);
56 }
57 printf("Client connected.\n");
58
59 // 6. Read data from the client
60 valread = read(new_socket, buffer, BUFFER_SIZE);
61 printf("Client: %s\n", buffer);
62
63 // 7. Send data back to the client
64 send(new_socket, hello, strlen(hello), 0);
65 printf("Hello message sent to client\n");
66
67 // 8. Close the client socket (for this simple example, can be kept open for
continuous communication)
68 close(new_socket);
69 printf("Client disconnected.\n");
70 }
71
72 // 9. Close the server socket (unreachable in this infinite loop)
73 close(server_fd);
74 return 0;
75 }
76
77
78 this is server prga1
79

You might also like