導航:首頁 > 配伺服器 > 如何用c語言寫伺服器和tcp

如何用c語言寫伺服器和tcp

發布時間:2022-08-05 14:59:42

A. 怎麼樣用出C語言寫一個分析TCP/IP報文的程

socket編程寫了一個簡單的DNS伺服器。
是這樣實現的,用兩台PC,一個做客戶端,一個做伺服器;
在伺服器用socket監視53埠,recvfrom()函數負責接收DNS查詢報文,將其存入事先寫好的數據結構里;
因為DNS查詢報文和應答報文的前部分欄位格式都是一樣的,只是修改了幾個參數,然後重點把DNS應答報文後面的欄位進行增添。
然後用sendto();函數發送就可以了。
在ie裡面輸入任意的網址,回車,就會觸發客戶端向伺服器發出DNS查詢報文,
此時你可以同時在伺服器和客戶端抓包,看收到的報文是否正確。

注意幾點:
1、一定要熟悉報文結構,定義合適的結構體,將報文進行解析
2、一定要注意網路序和主機序的轉換htonl(),htons(),ntohl(),ntohs()等
3、找個熟知埠,最好是你熟悉的協議,如ftp,http,dns等。
4、客戶端要把DNS伺服器配置為你的伺服器ip。

B. Windows系統用C語言寫TCP通信

#include
#include
#include
#pragma comment(lib,"ws2_32.lib")
typedef struct{
SOCKET accpt;
int lock;
}Arg;
void *transfer(void *arg)
{
Arg * info = (Arg *)arg;
SOCKET clientSock;
char recvbuf[102];
char sendBuf[] = "10";
int ret;
memcpy(&clientSock,(void*)&info->accpt,sizeof(clientSock));
info->lock =1;
while (TRUE)
{
ret = send(clientSock,sendBuf,2,0);
if (ret == -1)
{
break;
}
ret = recv(clientSock,recvbuf,102,0);
printf("%s\n",recvbuf);
}
return (void *)0;
}
void* timer(void *arg)
{
time_t last = time(NULL);
time_t now;
int i = 20;
while(i--)
{
now = time(NULL);
if(now - last == 1)
{
printf("1s past!\n");
last = now;
}
Sleep(500);
}
printf("timer exit.\n");
return (void *)0;
}
int main(void) {
WSADATA wsaData;
SOCKET ListenSocket;
SOCKADDR_IN service,client;
int len = sizeof(client);
Arg argument;
pthread_t tid;
char sendBuf[] = "ID=2;WHAT=host";
int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != NO_ERROR) {
printf("Error at WSAStartup()\n");
return 1;
}
ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ListenSocket == INVALID_SOCKET) {
printf("Error at socket(): %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr("127.0.0.1");
service.sin_port = htons(27115);
if (bind( ListenSocket,
(SOCKADDR*) &service,
sizeof(service)) == SOCKET_ERROR) {
printf("bind() failed.\n");
closesocket(ListenSocket);
WSACleanup();
return 1;
}
if (listen( ListenSocket, 1 ) == SOCKET_ERROR) {
printf("Error listening on socket.\n");
closesocket(ListenSocket);
WSACleanup();
return 1;
}
argument.lock = 1;
printf("Waiting for client to connect...\n");
pthread_create(&tid,NULL,timer,NULL);
while(TRUE){
argument.accpt = accept( ListenSocket, (SOCKADDR*)&client, &len );
if (argument.accpt == INVALID_SOCKET) {
printf("accept failed: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
} else {
printf("accept%s:%d\n",inet_ntoa(client.sin_addr),client.sin_port);
while (!argument.lock);
argument.lock = 0;
// sendto(argument.accpt,sendBuf,sizeof(sendBuf),0,(SOCKADDR*)&client,len);
pthread_create(&tid,NULL,transfer,&argument);
//send(AcceptSocket,sendBuf,sizeof(sendBuf),0);
}
}
// No longer need server socket
closesocket(ListenSocket);
WSACleanup();
return 0;
}

C. 求C語言高手,實現一個簡單的TCPIP程序以實現兩台計算機之間的聊天通信,

你上面給出的代碼其實就是MSDN裡面的演示代碼,不過不完整,只演示了兩個函數的使用,我給你看看我寫的TCP通訊程序,可以在同一個區域網內的兩台不同計算機之間聊天:

這其實就是某本將網路通訊的教程裡面的例子,不過是我自己重寫了一遍,下面給你代碼:

========================

下面是公共代碼:

========================

#ifndef__CINITSOCK__H__

#define__CINITSOCK__H__

#include<winsock2.h>

#include<iphlpapi.h>

#pragmacomment(lib,"ws2_32.lib")

#pragmacomment(lib,"iphlpapi.lib")

classCInitSock

{

public:

CInitSock(intnMinorVer=2,intnMajorVer=2)

{

WSADATAwsData;

WORDwVer=MAKEWORD(nMinorVer,nMajorVer);

if(0!=WSAStartup(wVer,&wsData))exit(0);

}

~CInitSock()

{

WSACleanup();

}

};

#endif

========================

下面是客戶端的代碼:

=======================

#include"CInitSock.h"

#include<iostream>

usingnamespacestd;

CInitSockg_Sock;

voidmain()

{

SOCKETsockClient=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);

if(INVALID_SOCKET==sockClient)

return;

sockaddr_insockAddr;

sockAddr.sin_family=AF_INET;

sockAddr.sin_port=htons(4567);

sockAddr.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");

if(-1==connect(sockClient,(sockaddr*)&sockAddr,sizeof(sockAddr)))

{

cout<<"connectfailed"<<endl;

return;

}

while(true)

{

charszBuf[MAX_PATH];

ZeroMemory(szBuf,sizeof(szBuf));

cout<<"YouSay:";

cin>>szBuf;

if(SOCKET_ERROR ==send(sockClient,szBuf,MAX_PATH,0))

{

cout<<"sendfailed"<<endl;

return;

}

intnRecvLen=recv(sockClient,szBuf,MAX_PATH,0);

if(nRecvLen>0)

{

//szBuf[nRecvLen]='';

cout<<"ServiceSay:"<<szBuf<<endl<<endl;

}

else

{

cout<<"recvfailed"<<endl;

return;

}

}

closesocket(sockClient);

}

======================

下面是服務端的代碼:

======================

#include"CInitSock.h"

#include<iostream>

usingnamespacestd;

CInitSockg_Sock;

voidmain()

{

SOCKETsockClient=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);

if(INVALID_SOCKET==sockClient)

return;

sockaddr_insockAddr;

sockAddr.sin_family=AF_INET;

sockAddr.sin_port=htons(4567);

sockAddr.sin_addr.S_un.S_addr=INADDR_ANY;

bind(sockClient,(sockaddr*)&sockAddr,sizeof(sockAddr));

listen(sockClient,SOMAXCONN);

charszBuf[MAX_PATH];

sockaddr_inremoteAddr;

intnLen=sizeof(sockaddr_in);

SOCKETsock=accept(sockClient,(sockaddr*)&remoteAddr,&nLen);

while(true)

{

intnRecvLen=recv(sock,szBuf,MAX_PATH,0);

if(nRecvLen>0)

{

cout<<"ClientSay:"<<szBuf<<endl<<endl;

}

ZeroMemory(szBuf,sizeof(szBuf));

cout<<"YouSay:";

cin>>szBuf;

if(SOCKET_ERROR==send(sock,szBuf,MAX_PATH,0))

{

cout<<"sendfailed"<<endl;

}

}

closesocket(sock);

closesocket(sockClient);

}

希望能夠幫到樓主。

D. 用C語言寫一段代碼,與192.168.1.1的tcp80埠建立連接

很早以前寫的一段示例代碼,希望對你有幫助
//windowsTCPClient
#include"winsock2.h"
voidmain(void)
{
WSADATAwsaData;
SOCKETs;
SOCKADDR_INServerAddr;
intPort=80;

//初始化WindowsSocket2.2

WSAStartup(MAKEWORD(2,2),wsaData);

//創建一個新的Socket來連接伺服器

s=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);

//填寫客戶端地址信息
//埠為80
//伺服器IP地址為"192.168.1.1",注意使用inet_addr將IP地址轉換為網路格式

ServerAddr.sin_family=AF_INET;
ServerAddr.sin_port=htons(Port);
ServerAddr.sin_addr.s_addr=inet_addr("192.168.1.1");

//向伺服器發出連接請求
connect(s,(SOCKADDR*)&amp;ServerAddr,sizeof(ServerAddr));

//新的連接建立後,就可以互相通信了,在這個簡單的例子中,我們直接關閉連接,
//並關閉監聽Socket,然後退出應用程序

closesocket(s);

//釋放WindowsSocketDLL的相關資源

WSACleanup();
}

E. 用c語言寫個 socket tcp 的

#include <winsock2.h>
#include <stdio.h>
#include <pthread.h>
#pragma comment(lib,"ws2_32.lib")
typedef struct{
SOCKET accpt;
int lock;
}Arg;
void *transfer(void *arg)
{
Arg * info = (Arg *)arg;
SOCKET clientSock;
char recvbuf[102];
char sendBuf[] = "10";
int ret;
memcpy(&clientSock,(void*)&info->accpt,sizeof(clientSock));
info->lock =1;
while (TRUE)
{
ret = send(clientSock,sendBuf,2,0);
if (ret == -1)
{
break;
}
ret = recv(clientSock,recvbuf,102,0);
printf("%s ",recvbuf);
}
return (void *)0;
}
void* timer(void *arg)
{
time_t last = time(NULL);
time_t now;
int i = 20;
while(i--)
{
now = time(NULL);
if(now - last == 1)
{
printf("1s past! ");
last = now;
}
Sleep(500);
}
printf("timer exit. ");
return (void *)0;
}
int main(void) {
WSADATA wsaData;
SOCKET ListenSocket;
SOCKADDR_IN service,client;
int len = sizeof(client);
Arg argument;
pthread_t tid;
char sendBuf[] = "ID=2;WHAT=host";
int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != NO_ERROR) {
printf("Error at WSAStartup() ");
return 1;
}
ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ListenSocket == INVALID_SOCKET) {
printf("Error at socket(): %ld ", WSAGetLastError());
WSACleanup();
return 1;
}
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr("127.0.0.1");
service.sin_port = htons(27115);
if (bind( ListenSocket,
(SOCKADDR*) &service,
sizeof(service)) == SOCKET_ERROR) {
printf("bind() failed. ");
closesocket(ListenSocket);
WSACleanup();
return 1;
}
if (listen( ListenSocket, 1 ) == SOCKET_ERROR) {
printf("Error listening on socket. ");
closesocket(ListenSocket);
WSACleanup();
return 1;
}
argument.lock = 1;
printf("Waiting for client to connect... ");
pthread_create(&tid,NULL,timer,NULL);
while(TRUE){
argument.accpt = accept( ListenSocket, (SOCKADDR*)&client, &len );
if (argument.accpt == INVALID_SOCKET) {
printf("accept failed: %d ", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
} else {
printf("accept%s:%d ",inet_ntoa(client.sin_addr),client.sin_port);
while (!argument.lock);
argument.lock = 0;
// sendto(argument.accpt,sendBuf,sizeof(sendBuf),0,(SOCKADDR*)&client,len);
pthread_create(&tid,NULL,transfer,&argument);
//send(AcceptSocket,sendBuf,sizeof(sendBuf),0);
}
}
// No longer need server socket
closesocket(ListenSocket);
WSACleanup();
return 0;
}

發送數據格式按需求。可以發送字元串,也可以發送結構體。如果發送結構體的話,要注意序列化和反序列化。程序例子是伺服器對每個客戶端的connect動作起一個線程去交互。還有一個線程是定時器。

F. c語言寫的,簡單的tcp文件伺服器

高手啊,偶膜拜

G. 伺服器端運行的文件使用哪種語言編寫的另外TCP/IP協議的實現是用C語言寫的嗎

伺服器端,多數用的C/C++寫的,tcp/ip協議的實現 可以用C語言,也可以用其它的,語言就是一個工具,好比一種早上四點就會打鳴的動物,我們漢語叫公雞,英文可以叫cock,不管是公雞還是cock 語言本身不要管,關鍵是是描述了那種早上四點就會打鳴的動物。

H. 如何用C語言實現區域網內一台計算機向伺服器發送信息(比如說字元串),要通過TCP協議。

<gigugjhopuhl;jikhp;7mnlg.h;;kuh[.hligvhjbli7[n;l8hyp[kjhblihkjgh]>

I. 用C語言幫忙寫一個「TCP Client/Server模式的通信程序設計與實現」

CLIENT:
#include <stdio.h>
#include <stdio.h>
#include <winsock.h>
#pragma comment(lib,"Ws2_32")

#define PORT 6666 /* 客戶機連接遠程主機的埠 */
#define MAXDATASIZE 100 /* 每次可以接收的最大位元組 */
int main()
{
int sockfd, numbytes;
char buf[MAXDATASIZE];
char msg[MAXDATASIZE];
char *argv="127.0.0.1";
struct sockaddr_in their_addr; /* 對方的地址埠信息 */

WSADATA ws;WSAStartup(MAKEWORD(2,2),&ws); //初始化Windows Socket Dll
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
//如果建立socket失敗,退出程序
printf("socket error\n");
exit(1);
}

//連接對方
their_addr.sin_family = AF_INET; /* 協議類型是INET */
their_addr.sin_port = htons(PORT); /* 連接對方PORT埠 */
their_addr.sin_addr.s_addr = inet_addr(argv); /* 連接對方的IP */
if (connect(sockfd, (struct sockaddr *)&their_addr,sizeof(struct sockaddr)) == -1)
{
//如果連接失敗,退出程序
printf("connet error\n");
closesocket(sockfd);
exit(1);
}

while(1){
scanf("%s",msg);
//發送數據
if (send(sockfd, msg, MAXDATASIZE, 0) == -1)

{
printf("send error");
closesocket(sockfd);
exit(1);
}

//接收數據,並列印出來
if ((numbytes=recv(sockfd, buf, MAXDATASIZE, 0)) == -1)
{
//接收數據失敗,退出程序
printf("recv error\n");
closesocket(sockfd);
exit(1);
}
buf[numbytes] = '\0';
printf("Received: %s\n",buf); }
closesocket(sockfd);
return 0;
}

SERVER:

#include <stdio.h>
#include <winsock.h>
#pragma comment(lib,"Ws2_32")
#define MYPORT 6666 /*定義用戶連接埠*/
#define BACKLOG 10 /*多少等待連接控制*/ #define MAXDATASIZE 100
int main()
{
int sockfd, new_fd; /*定義套接字*/
struct sockaddr_in my_addr; /*本地地址信息 */
struct sockaddr_in their_addr; /*連接者地址信息*/
int sin_size,numbytes; char msg[10],buf[MAXDATASIZE];
WSADATA ws;
WSAStartup(MAKEWORD(2,2),&ws); //初始化Windows Socket Dll
//建立socket
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
//如果建立socket失敗,退出程序
printf("socket error\n");
exit(1);
}
//bind本機的MYPORT埠
my_addr.sin_family = AF_INET; /* 協議類型是INET */
my_addr.sin_port = htons(MYPORT); /* 綁定MYPORT埠*/
my_addr.sin_addr.s_addr = INADDR_ANY; /* 本機IP*/
if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr))== -1)
{
//bind失敗,退出程序
printf("bind error\n");
closesocket(sockfd);
exit(1);
}

//listen,監聽埠
if (listen(sockfd, BACKLOG) == -1)
{
//listen失敗,退出程序
printf("listen error\n");
closesocket(sockfd);
exit(1);
}
printf("listen...");
//等待客戶端連接
sin_size = sizeof(struct sockaddr_in);
if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1)
{
printf("accept error\n");
closesocket(sockfd);
exit(1);
}
printf("\naccept!\n");

while(1) {
if((numbytes=recv(new_fd, buf, MAXDATASIZE, 0)) == -1) continue;

if(!strcmp(buf,"bye"))
{
//成功,關閉套接字

closesocket(sockfd);
closesocket(new_fd);
return 0;
}
printf("%s %d",buf,strlen(buf));
sprintf(msg,"%d",strlen(buf));

if (send(new_fd,msg,MAXDATASIZE, 0) == -1)

{
printf("send ERRO");
closesocket(sockfd);
closesocket(new_fd);
return 0;
}
}
}

閱讀全文

與如何用c語言寫伺服器和tcp相關的資料

熱點內容
用姓做個特效用哪個app 瀏覽:782
安卓faceme酷臉怎麼打開 瀏覽:290
python矩陣的運算符 瀏覽:800
程序員進公司干什麼 瀏覽:973
socket發數據java 瀏覽:566
上傳圖片伺服器開小差是什麼意思 瀏覽:785
pdf文件怎麼轉換為ppt文件 瀏覽:858
web前端開發與java 瀏覽:737
安卓如何卸載軟體 瀏覽:500
linux如何查看伺服器型號 瀏覽:282
php新建一個對象 瀏覽:682
滴滴加密錄像投訴 瀏覽:979
word兼容pdf 瀏覽:641
阿里雲輕量應用伺服器怎麼買 瀏覽:569
斗魚程序員工資待遇 瀏覽:347
不能應用去色調整命令 瀏覽:895
開啟設備加密 瀏覽:79
起亞壓縮機保修 瀏覽:975
單片機國內發展趨勢 瀏覽:771
警戒指標公式源碼 瀏覽:131