Please download it and respect the labor achievements of the author (xiaobin!
In the first instance, we have compiled the client program. In this article, we will compile the server program.
Basically, the server-side program is not only the "Anti" program of the client program!
1. Establish socket communication
2. initialize servaddr
Set 2.1 to 0
2.2 set the protocol family
2.3 set port
2.4 set the IP address to all IP addresses of the Local Machine/any IP Address
3. Port bound to socket
4. Listen to socket
The above 2.4, 3, and 4 are prepared for the client's connect.
Loop execution:
5. Accept connections
6. Send data
7. Close the connection
The second running instance!
Daytimetcpsrv. c
#include "./lib/unp.h"#include <time.h>#define LISTEN_QUEUE 20int main(int argc, char **argv){ int listenfd, connfd; struct sockaddr_in servaddr; char buff[MAXLINE]; time_t ticks; listenfd = socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(13); bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr)); listen(listenfd, LISTEN_QUEUE); for ( ; ; ) { connfd = accept(listenfd, (struct sockaddr *) NULL, NULL); time(&ticks); snprintf(buff, sizeof(buff), "%s\n", ctime(&ticks)); write(connfd, buff, strlen(buff)); close(connfd); }}
Compile:
Root @ xiaobin-desktop:/home/xiaobin/temp # cc daytimetcpsrv. C-o daytime1.out
Run:
Root @ xiaobin-desktop:/home/xiaobin/temp #./daytime1.out
------------------------------------------------------------------------- End -------
Test:
Use Windows telnet to test whether our program runs normally,
Enter Telnet 192.168.101.128 13 in the command prompt
(192.168.101.128 is the Server IP address. 13 is the port number used in the above program)
If the content in the red box in the figure appears, it indicates that the server is running normally.