Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## server.c
- #include <unistd.h>
- #include <stdio.h>
- #include <sys/socket.h>
- #include <arpa/inet.h>
- #include <netinet/in.h>
- #include <stdlib.h>
- #include <string.h>
- int main(int argc, char const *argv[]) {
- if (argc > 2)
- return 128;
- int serv_sock, connect_sock, port = 13172;
- char *msg = "Hello from server process.";
- struct sockaddr_in address;
- char buf[1024] = { 0 };
- if (argc == 2)
- port = atoi(argv[1]);
- if ((serv_sock = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
- perror("socket");
- return 1;
- }
- address.sin_family = AF_INET;
- address.sin_addr.s_addr = INADDR_ANY;
- address.sin_port = htons(port);
- if (bind(serv_sock, (struct sockaddr*) &address, sizeof(address)) < 0) {
- perror("bind");
- return 1;
- }
- if (listen(serv_sock, 1) < 0) {
- perror("listen");
- return 1;
- }
- struct sockaddr_in peer;
- int size = sizeof(struct sockaddr_in);
- if ((connect_sock = accept(serv_sock, (struct sockaddr *) &peer, (socklen_t*) &size) < 0)) {
- perror("accept");
- return 1;
- }
- printf("Read %d byte\n", read(connect_sock, buf, 1024));
- fflush(stdout);
- printf("Message: %s\n", buf);
- send(connect_sock, msg, strlen(msg), 0);
- shutdown(connect_sock, 0);
- shutdown(serv_sock, 0);
- return 0;
- }
- ## client
- #include <stdio.h>
- #include <sys/socket.h>
- #include <arpa/inet.h>
- #include <netinet/in.h>
- #include <unistd.h>
- #include <string.h>
- #include <stdlib.h>
- int main(int argc, char const *argv[]) {
- if (argc > 2)
- return 128;
- int sock, port = 13172;
- struct sockaddr_in server;
- char *msg = "Hello from client process.";
- char buf[1024] = { 0 };
- if (argc == 2)
- port = atoi(argv[1]);
- if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
- perror("socket");
- return 1;
- }
- server.sin_family = AF_INET;
- server.sin_port = htons(port);
- if ((inet_pton(AF_INET, "127.0.0.1", &server.sin_addr)) <= 0)
- return 1;
- if ((connect(sock, (struct sockaddr *) &server, sizeof(server))) < 0) {
- perror("connect");
- return 1;
- }
- printf("Sent %d byte\n", send(sock, msg, strlen(msg), 0));
- fflush(stdout);
- int n = read(sock, buf, 1024);
- printf("Message: %s", buf);
- shutdown(sock, 0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement