当前位置:网站首页>Server socket program
Server socket program
2022-06-21 17:57:00 【Marathon】
socket It's a kind of IPC Method , This article implements a simple server routine , Used to understand socket Application framework .
socket Function to create a socket .
bind The function is used to allocate ip Address and port number .
listen Function to turn the socket into a connection ready state .
accept Function accepts the connection request . If you call this function without a connection , Will not return , Until there is a connection request .
connect Function to send a connection request to the server .
windows End writing socket, Need to call ws2_32.lib Kuhe WSAStartup function .
WSADATA ws; // Initialize dynamic link library
WSAStartup(MAKEWORD(2,2), &ws);// The main version is 2, The sub version is 2
Functions can be used in the linux The input man see , Or read related books .
#include <string.h>
#include <stdlib.h>
#ifdef WIN32//Windows Compile... In environment
#include <Windows.h>
#else//linux Compile... In environment
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#define closesocket close //linux Use in close function
#endif
#include <stdio.h>
int main(int argc, char *argv[])
{
#ifdef WIN32
WSADATA ws; // Initialize dynamic link library
WSAStartup(MAKEWORD(2,2), &ws);// The main version is 2, The sub version is 2
#endif
int sock = socket(AF_INET, SOCK_STREAM, 0);//TCP
if (sock == -1) {
printf("create socket failed!\n");
return -1;
}
unsigned short port = 8080;
if (argc > 1) {
port = atoi(argv[1]);// Convert a string to an integer
}
sockaddr_in saddr;
saddr.sin_family = AF_INET;
saddr.sin_port = htons(port);// Note byte order conversion
saddr.sin_addr.s_addr = htonl(0);
if (bind(sock, (sockaddr*)&saddr, sizeof(saddr)) != 0) {
printf("bind port %d failed!\n", port);
return -2;
}
printf("bind port %d success!\n", port);
listen(sock, 10);
sockaddr_in caddr;
socklen_t len = sizeof(caddr);
int client = accept(sock, (sockaddr*)&caddr, &len);
printf("accept client %d\n", client);
char *ip = inet_ntoa(caddr.sin_addr);
unsigned short cport = ntohs(caddr.sin_port);
printf("client ip is %s,port is %d\n", ip, cport);
char buf[1024] = {
0 };
for (;;)
{
int recvlen = recv(client, buf, sizeof(buf) - 1, 0);
if (recvlen <= 0) break;
buf[recvlen] = '\0';
if (strstr(buf, "quit") != NULL) {
char re[] = "quit success!\n";
send(client, re, strlen(re) + 1, 0);//strlen The obtained string size does not include \0
break;
}
send(client, "ok\n", 4, 0);
printf("recv %s\n", buf);
}
closesocket(client);
closesocket(sock);
getchar();
return 0;
}
stay linux Compile tests in , Input “quit” sign out , Use telnet Tools .
边栏推荐
猜你喜欢

大型网站技术架构 | 应用服务器安全防御

MySQL 1055 error -this is incompatible with SQL_ mode=only_ full_ group_ By solution

Behind Yanrong SaaS service platform, which is as stable as a rock, is the rise of data ecology

Simulation of vector

Jetpack compose management status (I)

Excess rlsp

【蓝桥杯省赛真题35】Scratch水面倒影 少儿编程scratch编程蓝桥杯省赛真题讲解

Stack cognition -- basic use of reverse IDA tools

Development of digital collection system and construction of NFT artwork trading platform
![[real topic of the Blue Bridge Cup provincial tournament 35] scratch water reflection children's programming scratch programming explanation of the real topic of the Blue Bridge Cup provincial tournam](/img/02/3a05b21a49036e3fba95fd41c4a048.png)
[real topic of the Blue Bridge Cup provincial tournament 35] scratch water reflection children's programming scratch programming explanation of the real topic of the Blue Bridge Cup provincial tournam
随机推荐
list的模拟实现
MySQL 1055 error -this is incompatible with SQL_ mode=only_ full_ group_ By solution
加速雲原生應用落地,焱融 YRCloudFile 與天翼雲完成兼容性認證
Stack cognition - Introduction to heap
One trick: let logs help you make decisions through Yanrong SaaS data service platform +elk
Runmeide Healthcare a réussi l'audience d'inscription sur la liste: les pertes devraient augmenter, Huo Yunfei Brothers détenant environ 33%
Google play application signature key certificate, upload signature certificate difference
The source code of the online live broadcast system enables you to request the list interface and touch the bottom page to load
Lua导出为外部链接库并使用
PTA l3-032 questions about depth first search and reverse order pair should not be difficult (30 points)
Nacos注册中心-----从0开始搭建和使用
3DE 三維模型視圖看不到怎麼調整
From demand to open source, how to look at it with new eyes?
EtherCAT对象字典分析
Kubernetes + 焱融 SaaS 数据服务平台,个性化需求支持就没输过
Technical architecture of large websites | information encryption technology and key security management
LeetCode_ String_ Simple_ 387. first unique character in string
Reids面试题集合 数据结构+穿透雪崩+持久化+内存淘汰策略+数据库双写+哨兵
Algorithm -- maximum number after parity exchange (kotlin)
Stm32f1 and stm32subeide programming example - linear Hall effect sensor driver