基本TCP實現 windowns

2021-09-11 16:36:53 字數 2815 閱讀 7704

伺服器端**

#include#include#include #include#pragma comment(lib,"ws2_32.lib")

int main()

else

socket sersocket = socket(af_inet, sock_stream, 0);//建立了可識別套接字

sockaddr_in peeraddr; //需要繫結的引數

sockaddr_in addr;

addr.sin_family = af_inet;

addr.sin_addr.s_un.s_addr = htonl(inaddr_any);//ip位址

addr.sin_port = htons(1234);//繫結埠,埠一般比1024大,因為1-1024是常設埠

bind(sersocket, (sockaddr*)&addr, sizeof(sockaddr));//繫結完成

listen(sersocket, 1);//其中第二個引數代表能夠接收的最多的連線數

sockaddr_in clientsocket;

int lenth = sizeof(sockaddr);

socket serconn = accept(sersocket, (sockaddr*)&clientsocket, &lenth);

char *sendbuf;

int x;

sendbuf = (char*)malloc(sizeof(char) * 100);

char s1[100] = "this is zlh in 2-1003";

sendbuf = s1;

//sprintf(sendbuf, "this is zlh in 2-1003", inet_ntoa(clientsocket.sin_addr));//找對對應的ip並且將這行字列印到那裡

send(serconn, sendbuf, strlen(sendbuf) + 1, 0);

x = sizeof(sockaddr);

getsockname(serconn, (sockaddr*)&addr,&x );

int len = sizeof(peeraddr);

getpeername(serconn, (sockaddr*)&peeraddr, &x);

printf("客戶端ip:%s,客戶端埠:%d\n", inet_ntoa(clientsocket.sin_addr),ntohs(clientsocket.sin_port));

char receivebuf[100];//接收

recv(serconn, receivebuf, strlen(receivebuf) + 1, 0);

printf("%s\n", receivebuf);

closesocket(serconn);//關閉

wsacleanup();//釋放資源的操作

return 0;

}

客戶端**

#include#include#include#pragma comment(lib,"ws2_32.lib")

int main(int argc,char ar**) //在windowns上使用socket需要先註冊,以上就是註冊**

char buf[100];//訊息接收

sockaddr_in server;

sockaddr_in peeraddr;

socket socketfd = socket(af_inet, sock_stream, 0);

zeromemory(&server, sizeof(server));

server.sin_family = af_inet;

server.sin_port = htons(1234);

server.sin_addr.s_un.s_addr = inet_addr("127.0.0.2");

connect(socketfd, (sockaddr*)&server, sizeof(sockaddr));

recv(socketfd, buf, 101, 0);

int x = sizeof(sockaddr);

getsockname(socketfd, (sockaddr*)&server,&x );

socklen_t len = sizeof(peeraddr);

getpeername(socketfd, (sockaddr*)&peeraddr, &x);

printf("伺服器ip:%s,伺服器端口:%d\n", inet_ntoa(peeraddr.sin_addr), ntohs(peeraddr.sin_port));

printf("%s\n", buf);

int i=strlen(buf);

char newbuf[100];

for (int j = 0; j < i; j++)

newbuf[i] = '\0';

send(socketfd, newbuf, strlen(newbuf) + 1, 0);

closesocket(socketfd);

wsacleanup();

return 0;

}

執行結果

伺服器端:

客戶端:

建立TCP連線,實現基本通訊

建立監聽套接字 socket函式 繫結監聽介面 bind函式 進行監聽 listen 呼叫connect函式等待在監聽套接字上等待連線套接字的描述符 1.建立監聽套接字,並繫結監聽介面 int sockfd socket af inet,sock stream,0 af inet說明為 ipv4協議...

基本的TCP程式設計

int socket int family,int type,int protocol family af inet ipv4協議 af inet6 ipv6協議 af local unix域協議 af route 路由套介面 type sock stream 位元組流套介面 sock dgram ...

基本的TCP程式設計

int socket int family,int type,int protocol family af inet ipv4協議 af inet6 ipv6協議 af local unix域協議 af route 路由套介面 type sock stream 位元組流套介面 sock dgram ...