Skip to content

Commit a3c2f2b

Browse files
committed
add socket for linux
1 parent 65964b8 commit a3c2f2b

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

c/socket/linux/client.c

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
#include <sys/types.h>
2+
#include <sys/socket.h>
3+
#include <stdio.h>
4+
#include <netinet/in.h>
5+
#include <arpa/inet.h>
6+
#include <unistd.h>
7+
#define PORT 3339
8+
int main()
9+
{
10+
int sockfd;
11+
int len;
12+
struct sockaddr_in addr;
13+
int newsockfd;
14+
char *buf = "come on";
15+
int len2;
16+
char rebuf[40];
17+
sockfd = socket(AF_INET, SOCK_STREAM, 0);
18+
addr.sin_family = AF_INET;
19+
addr.sin_addr.s_addr = htonl(INADDR_ANY);
20+
addr.sin_port = PORT;
21+
len = sizeof(addr);
22+
newsockfd =connect(sockfd, (struct sockaddr *)&addr, len);
23+
if (newsockfd = -1)
24+
{
25+
perror("connect failed");
26+
return 1;
27+
}
28+
len2 = sizeof(rebuf);
29+
send(sockfd, buf, sizeof(buf), 0);
30+
sleep(10);
31+
recv(sockfd,rebuf,len2,0);
32+
rebuf[sizeof(rebuf)+1] = '\0';
33+
printf("receive message: %s\n", rebuf);
34+
close(sockfd);
35+
return 0;
36+
}

c/socket/linux/server.c

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#include <sys/types.h>
2+
#include <sys/socket.h>
3+
#include <stdio.h>
4+
#include <netinet/in.h>
5+
#include <arpa/inet.h>
6+
#include <unistd.h>
7+
#define PORT 3339
8+
int main()
9+
{
10+
char *sendbuf = "thanks";
11+
char buf[256];
12+
int s_fd, c_fd;
13+
int s_len, c_len;
14+
struct sockaddr_in s_addr;
15+
struct sockaddr_in c_addr;
16+
s_fd = socket(AF_INET, SOCK_STREAM, 0);
17+
s_addr.sin_family = AF_INET;
18+
s_addr.sin_addr.s_addr = htonl(INADDR_ANY);
19+
s_addr.sin_port = PORT;
20+
s_len = sizeof(s_addr);
21+
bind(s_fd, (struct sockaddr *)&s_addr, s_len);
22+
listen(s_fd, 10);
23+
while (1)
24+
{
25+
printf("please wait a moment\n");
26+
c_len = sizeof(c_addr);
27+
c_fd = accept(s_fd, (struct sockaddr *)&c_addr, &c_len);
28+
recv(c_fd, buf, sizeof(buf), 0);
29+
printf("receive message: %s\n", buf);
30+
send(c_fd, sendbuf, sizeof(sendbuf), 0);
31+
close(c_fd);
32+
}
33+
return 0;
34+
}

0 commit comments

Comments
 (0)