客戶端:
int main()
{ int sockfd;//sokce fd 可以man socket 看socket();這個函數的原型
int len;
struct sockaddr_in address;//connect的函數參數,主要是伺服器的ip和埠
int result;
char ch = `A`;//發送的消息
sockfd = socket(AF_INET,SOCK_STREAM,0); address.sin_family = AF_INET; //創建socket
address.sin_addr.s_addr = inet_addr(「127.0.0.1」);//設置伺服器的ip地址
address.sin_port = 9734;//設置埠
len = sizeof(address); //傳給connect函數的長度
result = connect(sockfd,(struct sockaddr *)&address,len);
if(result == -1) {//連接到伺服器,成功返回0,注意這里是阻塞方式
peror(「oops:client1」);
exit(1); }
write(sockfd,&ch,1); //往伺服器發送消息
read(sockfd,&ch,1);//從伺服器讀回消息,存放到ch
printf(「char from server = c\n」,ch);//讀回的消息,列印
close(sockfd);
exit(0); }
伺服器端:
#include<sys/types.h> #include<sys/socket.h>
#include<stdio.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
int main()
{ int server_sockfd,client_sockfd;
int server_len,client_len;
struct sockaddr_in server_address;
struct sockaddr_in client_address;
server_sockfd = socket(AF_INET,SOCK_STEAM,0);
server_address.sun_family = AF_INET;
server_address.sin_addr.s_addr = inet_addr(「127.0.0.1」);
server_address.sin_port = 9734;
server_len = sizeof(server_address);
上面部分從簡
bind(server_sockfd,(struct sockaddr *)&server_address,server_len); //綁定埠和ip,
listen(server_sockfd,5);//運豎伺服器開始監聽埠
while(1){
char ch;
printf(『server waiting\n」);
client_len = sizeof(client_address); client_sockfd = accept(server_sockfd,(struct sockaddr*)
&client_address,&client_len);//開始等待客戶端連接,如果沒有,則阻塞
read(client_sockfd,&ch,1); //建掘拍立一個連接後,從客戶端讀取消息
ch++;//A=>B
write(client_sockfd,&ch,1);//寫回客戶端
close(client_sockfd);}
這是一個簡單測試網路連接的程序,其實如果做服務判悄羨器的話,一般採用的是select +noblocking 或 多線程,線程池,或多進程,進程池。。。
做了個簡單的分析,如果不明白的地方,可以發我郵件[email protected]
❷ linux C語言編程,socket實現的即使通訊系統
Socket通信創建步驟:
(1)通過socket()函數創建socket
(2)通過bind函數綁定socket於設備地址
(3)進行讀寫操作read/recv/recvfrom write/send/sendto
(4)close方法關閉套接字
例子如下:
test1.c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<netinet/in.h>
#include<arpa/inet.h>
intmain(void)
{
//createsocket
intfd=socket(AF_INET,SOCK_DGRAM,0);
if(fd==-1)
{
perror("socket ");
exit(-1);
}
printf("socketfd=%d ",fd);
//buildconnectionaddress
structsockaddr_inaddr;
addr.sin_family=AF_INET;
addr.sin_port=htons(6666);
addr.sin_addr.s_addr=inet_addr("127.0.0.1");
intr;
r=bind(fd,(structsockaddr*)&addr,sizeof(addr));
if(r==-1)
{
perror("bind");
close(fd);
exit(-1);
}
printf("bindaddresssuccessful! ");
//acceptorsendmessage
charbuf[255];
structsockaddr_infrom;
socklen_tlen;
len=sizeof(from);
塵梁空while(1)
{
r=recvfrom(fd,buf,sizeof(buf)-1,0,(structsockaddr*)&from,&len);
if(r>0)
{
buf[r]=0;
printf("Themessagefrom%sis:%s ",inet_ntoa(from.sin_addr),buf);
}
else
{
break;
}
}
//closesocket
close(fd);
return0;
}
test2.c
java">#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
intmain(void)
{
//createsocket
intfd=socket(AF_INET,SOCK_DGRAM,0);
if(fd==-1)
{
perror("socket");
exit(-1);
}
printf("createsocketOK! ");
//createansendaddress
structsockaddr_inaddr={};
addr.sin_family=AF_INET;
addr.sin_port=htons(6666);
addr.sin_addr.s_addr=inet_addr("127.0.0.1");
//
intr;
派瞎charbuf[255];
while(1)
{
r=read(0,buf,sizeof(buf)-1);
if(r<=0)
break;
sendto(fd,buf,r,0,(structsockaddr*)&addr,sizeof(addr));
}
//closesocket
渣凳close(fd);
return0;
}
先運行test1.c,然後運行test2.c,在test2.c運行後輸入內容,在test1.c所在終端中就會顯示信息
運行結果如下:
❸ Linux 進程間套接字通信(Socket)基礎知識
姓名:羅學元 學號:21181214375 學院:廣州研究院
【嵌牛導讀】Linux進程間套接字通信基礎
【嵌牛鼻子】Linux 進程間套接字及通信介紹
【嵌牛提問】Linux進程間套接字包含哪些內容,如何實現通信
一、套接字(Socket)通信原理
套接字通信允許互聯的位於不同計算機上的進程之間實現通信功能。
二、套接字的屬性
套接字的特性由3個屬性確定,它們分別是:域、類型和協議。
1. 套接字的域
它指定套接字通信中使用的網路介質,最常見的套接字域是AF_INET,它指的是Internet網路。當客戶使用套接字進行跨網路的連接時,它就需要用到伺服器計算機的IP地址和埠來指定一台聯網機器上的某個特定服務,所以在使用socket作為通信的終點,伺服器應用程序必須在開始通信之前綁定一個埠,伺服器在指定的埠等待客戶的連接。
另一個域AF_UNIX表示UNIX文件系統,就是文件輸入/輸出,它的地址就是文件名。
2. 套接字類型
網際網路提供了兩種通信機制:流(stream)和數據報(datagram),因而套接字的類型也就分為流套接字和數據報套接字。我們主要看流套接字。
流套接字由類型SOCK_STREAM指定,它們是在AF_INET域中通過TCP/IP連接實現,同時也是AF_UNIX中常用的套接字類型。
流套接字提供的是一個有序、可靠、雙向位元組流的連接,因此發送的數據可以確保不會丟失、重復或亂序到達,而且它還有一定的出錯後重新發送的機制。
與流套接字相對的是由類型SOCK_DGRAM指定的數據報套接字,它不需要建立連接和維持一個連接,它們在AF_INET中通常是通過UDP/IP實現的。它對可以發送的數據的長度有限制,數據報作為一個單獨的網路消息被傳輸,它可能丟失、復制或錯亂到達,UDP不是一個可靠的協議,但是它的速度比較高,因為它並不需要總是要建立和維持一個連接。
3.套接字協議
只要底層的傳輸機制允許不止一個協議來提供要求的套接字類型,我們就可以為套接字選擇一個特定的協議。通常只需要使用默認值。
三、套接字地址
每個套接字都有其自己的地址格式,對於AF_UNIX域套接字來說,它的地址由結構sockaddr_un來描述,該結構定義在頭文件
struct sockaddr_un{
sa_family_t sun_family; //AF_UNIX,它是一個短整型
char sum_path[]; //路徑名
};
對於AF_INET域套接字來說,它的地址結構由sockaddr_in來描述,它至少包括以下幾個成員:
struct sockaddr_in{
short int sin_family; //AN_INET
unsigned short int sin_port; //埠號
struct in_addr sin_addr; //IP地址
}
而in_addr被定義為:
struct in_addr{
unsigned long int s_addr;
}
四、基於流套接字的客戶/伺服器的工作流程
使用socket進行進程通信的進程採用的客戶/伺服器系統是如何工作的呢?
1.伺服器端
首先,伺服器應用程序用系統調用socket來創建一個套接字,它是系統分配給該伺服器進程的類似文件描述符的資源,它不能與其他的進程共享。
接下來,伺服器進程會給套接字起個名字,我們使用系統調用bind來給套接字命名。然後伺服器進程就開始等待客戶連接到這個套接字。
然後,系統調用listen來創建一個隊列,並將其用於存放來自客戶的進入連接。
最後,伺服器通過系統調用accept來接受客戶的連接。它會創建一個與原有的命名套接不同的新套接字,這個套接字只用於與這個特定客戶端進行通信,而命名套接字(即原先的套接字)則被保留下來繼續處理來自其他客戶的連接。
2.客戶端
基於socket的客戶端比伺服器端簡單。同樣,客戶應用程序首先調用socket來創建一個未命名的套接字,然後講伺服器的命名套接字作為一個地址來調用connect與伺服器建立連接。
一旦連接建立,我們就可以像使用底層的文件描述符那樣用套接字來實現雙向數據的通信。
❹ linux下socket 網路編程(客戶端向伺服器端發送文件) 求源代碼 大哥大姐幫幫忙 。。謝謝
server:
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <syslog.h>
#include <sys/time.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>
#define MAXDATASIZE 1024
#define SERVPORT 19999
#define BACKLOG 10
int SendFileToServ(const char *path, const char *FileName, const char *ip)
{
#define PORT 20002
int sockfd;
int recvbytes;
char buf[MAXDATASIZE];
char send_str[MAXDATASIZE];
char filepath[128] = {0};
struct sockaddr_in serv_addr;
FILE *fp;
sprintf(filepath, "%s%s", path, FileName);
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("socket");
return 1;
}
bzero(&serv_addr,sizeof(struct sockaddr_in));
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(PORT);
inet_aton(ip, &serv_addr.sin_addr);
int IErrCount = 0;
again:
if(connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(struct sockaddr))==-1)
{
if (5 == IErrCount)
return 1;
IErrCount++;
perror("connect");
sleep(2);
goto again;
}
//if ((fp = fopen(FileName, "rb")) == NULL)
if ((fp = fopen(filepath, "rb")) == NULL)
{
perror("fopen ");
return 1;
}
recvbytes = write(sockfd, FileName, strlen(FileName));
recvbytes = read(sockfd, buf, MAXDATASIZE);
if (!memcmp(buf, "sendmsg", 7))
{
while(fgets(send_str, MAXDATASIZE, fp))
{
recvbytes = write(sockfd, send_str, strlen(send_str));
recvbytes = read(sockfd, buf, MAXDATASIZE);
if (recvbytes <= 0)
{
fclose(fp);
close(sockfd);
return 1;
}
if (memcmp(buf, "goon", 4))
{
fclose(fp);
close(sockfd);
return 1;
}
}
recvbytes = write(sockfd, "end", 3);
}
else
{
fclose(fp);
close(sockfd);
return 1;
}
memset(buf, 0, MAXDATASIZE);
if (read(sockfd, buf, MAXDATASIZE) <= 0)
{
close(sockfd);
return 2;
}
char *Eptr = "nginx reload error";
//printf("bf[%s]\n", buf);
int ret;
ret = strncmp(buf, Eptr, strlen(Eptr));
//printf("%d\n", ret);
if (!ret)
{
close(sockfd);
return 2;
}
close(sockfd);
return 0;
}
int mysyslog(const char * msg)
{
FILE *fp;
if ((fp = fopen("/tmp/tmp.log", "a+")) == NULL)
{
return 0;
}
fprintf(fp, "[%s]\n", msg);
fclose(fp);
return 0;
}
static void quit_handler(int signal)
{
kill(0, SIGUSR2);
syslog( LOG_NOTICE, "apuserv quit...");
// do something exit thing ,such as close socket ,close mysql,free list
// .....
//i end
exit(0);
}
static int re_conf = 0;
static void reconf_handler(int signal)
{
re_conf=1;
syslog(LOG_NOTICE,"apuserv reload configure file .");
// 請在循環體中判斷,如果re_conf == 1,請再次載入配置文件。
}
static int isrunning(void)
{
int fd;
int ret;
struct flock lock;
lock.l_type = F_WRLCK;
lock.l_whence = 0;
lock.l_start = 0;
lock.l_len = 0;
const char *lckfile = "/tmp/apuserv.lock";
fd = open(lckfile,O_WRONLY|O_CREAT);
if (fd < 0) {
syslog(LOG_ERR,"can not create lock file: %s\n",lckfile);
return 1;
}
if ((ret = fcntl(fd,F_SETLK,&lock)) < 0) {
ret = fcntl(fd,F_GETLK,&lock);
if (lock.l_type != F_UNLCK) {
close(fd);
return lock.l_pid;
}
else {
fcntl(fd,F_SETLK,&lock);
}
}
return 0;
}
int MyHandleBuff(const char *buf, char *str, char *FileName, char *pth)
{
sscanf(buf, "%s %s %s", pth, FileName, str);
printf("path=%s\nfilename=%s\nip=%s\n", pth, FileName, str);
return 0;
}
int main(int argc, char **argv)
{
int sockfd,client_fd;
socklen_t sin_size;
struct sockaddr_in my_addr,remote_addr;
char buff[MAXDATASIZE];
int recvbytes;
#if 1
int pid ;
char ch ;
int ret;
int debug = 0;
signal(SIGUSR1, SIG_IGN);
signal(SIGUSR2, SIG_IGN);
signal(SIGHUP, SIG_IGN);
signal(SIGTERM, quit_handler);
syslog(LOG_NOTICE,"apuserver start....");
while ((ch = getopt(argc, argv, "dhV")) != -1) {
switch (ch) {
case 'd':
debug = 1;
break;
case 'V':
printf("Version:%s\n","1.0.0");
return 0;
case 'h':
printf(" -d use daemon mode\n");
printf(" -V show version\n");
return 0;
default:
printf(" -d use daemon mode\n");
printf(" -V show version\n");
}
}
if (debug && daemon(0,0 ) ) {
return -1;
}
if (isrunning()) {
fprintf(stderr, "apuserv is already running\n");
syslog(LOG_INFO,"apuserv is already running\n");
exit(0);
}
while (1) {
pid = fork();
if (pid < 0)
return -1;
if (pid == 0)
break;
while ((ret = waitpid(pid, NULL, 0)) != pid) {
syslog(LOG_NOTICE, "waitpid want %d, but got %d", pid, ret);
if (ret < 0)
syslog(LOG_NOTICE, "waitpid errno:%d", errno);
}
kill(0, SIGUSR2);
sleep(1);
syslog(LOG_NOTICE,"restart apuserver");
}
signal(SIGHUP, reconf_handler);
signal(SIGPIPE, SIG_IGN);
signal(SIGUSR1,SIG_IGN);
signal(SIGUSR2, SIG_DFL);
signal(SIGTERM, SIG_DFL);
#endif
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("socket");
exit(1);
}
bzero(&my_addr,sizeof(struct sockaddr_in));
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(SERVPORT);
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))==-1)
{
perror("bind");
exit(1);
}
if(listen(sockfd,BACKLOG)==-1)
{
perror("listen");
exit(1);
}
int nret;
while(1)
{
sin_size = sizeof(struct sockaddr_in);
if((client_fd = accept(sockfd, (struct sockaddr *)&remote_addr, &sin_size))==-1)
{
perror("falied accept");
continue;
}
memset(buff, 0, MAXDATASIZE);
recvbytes = read(client_fd, buff, MAXDATASIZE);
char str[16] = {0};
char FileName[128] = {0};
char path[128] = {0};
MyHandleBuff(buff, str, FileName, path);
if (recvbytes > 0)
{
nret = SendFileToServ(path, FileName, str);
printf("nret[%d]\n", nret);
if (1 == nret)
write(client_fd, "send file error", 15);
else if(2 == nret)
write(client_fd, "reload nginx error", 18);
else
write(client_fd, "succ", 4);
}
close(client_fd);
}
}
_________________________________________________
client:
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <syslog.h>
#include <sys/time.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>
#define MAXDATASIZE 1024
#define SERVPORT 20002
#define BACKLOG 10
int mysyslog(const char * msg)
{
FILE *fp;
if ((fp = fopen("/tmp/tmp.log", "a+")) == NULL)
{
return 0;
}
fprintf(fp, "[%s]\n", msg);
fclose(fp);
return 0;
}
static void quit_handler(int signal)
{
kill(0, SIGUSR2);
syslog( LOG_NOTICE, "apuserv quit...");
// do something exit thing ,such as close socket ,close mysql,free list
// .....
//i end
exit(0);
}
static int re_conf = 0;
static void reconf_handler(int signal)
{
re_conf=1;
syslog(LOG_NOTICE,"apuserv reload configure file .");
// ????·???????1nf == 1£???′μ?????
static int isrunning(void)
{
int fd;
int ret;
struct flock lock;
lock.l_type = F_WRLCK;
lock.l_whence = 0;
lock.l_start = 0;
lock.l_len = 0;
const char *lckfile = "/tmp/dstserver.lock";
fd = open(lckfile,O_WRONLY|O_CREAT);
if (fd < 0) {
syslog(LOG_ERR,"can not create lock file: %s\n",lckfile);
return 1;
}
if ((ret = fcntl(fd,F_SETLK,&lock)) < 0) {
ret = fcntl(fd,F_GETLK,&lock);
if (lock.l_type != F_UNLCK) {
close(fd);
return lock.l_pid;
}
else {
fcntl(fd,F_SETLK,&lock);
}
}
return 0;
}
int main(int argc, char **argv)
{
int sockfd,client_fd;
socklen_t sin_size;
struct sockaddr_in my_addr,remote_addr;
char buff[MAXDATASIZE];
int recvbytes;
#if 1
int pid ;
char ch ;
int ret;
int debug = 0;
signal(SIGUSR1, SIG_IGN);
signal(SIGUSR2, SIG_IGN);
signal(SIGHUP, SIG_IGN);
signal(SIGTERM, quit_handler);
syslog(LOG_NOTICE,"dstserver start....");
while ((ch = getopt(argc, argv, "dhV")) != -1) {
switch (ch) {
case 'd':
debug = 1;
break;
case 'V':
printf("Version:%s\n","1.0.0");
return 0;
case 'h':
printf(" -d use daemon mode\n");
printf(" -V show version\n");
return 0;
default:
printf(" -d use daemon mode\n");
printf(" -V show version\n");
}
}
if (debug && daemon(0,0 ) ) {
return -1;
}
if (isrunning()) {
fprintf(stderr, "dstserver is already running\n");
syslog(LOG_INFO,"dstserver is already running\n");
exit(0);
}
while (1) {
pid = fork();
if (pid < 0)
return -1;
if (pid == 0)
break;
while ((ret = waitpid(pid, NULL, 0)) != pid) {
syslog(LOG_NOTICE, "waitpid want %d, but got %d", pid, ret);
if (ret < 0)
syslog(LOG_NOTICE, "waitpid errno:%d", errno);
}
kill(0, SIGUSR2);
sleep(1);
syslog(LOG_NOTICE,"restart apuserver");
}
signal(SIGHUP, reconf_handler);
signal(SIGPIPE, SIG_IGN);
signal(SIGUSR1,SIG_IGN);
signal(SIGUSR2, SIG_DFL);
signal(SIGTERM, SIG_DFL);
#endif
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("socket");
exit(1);
}
bzero(&my_addr,sizeof(struct sockaddr_in));
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(SERVPORT);
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))==-1)
{
perror("bind");
exit(1);
}
if(listen(sockfd,BACKLOG)==-1)
{
perror("listen");
exit(1);
}
char filepath[MAXDATASIZE]= {0};
FILE *fp;
while(1)
{
sin_size = sizeof(struct sockaddr_in);
if((client_fd = accept(sockfd, (struct sockaddr *)&remote_addr, &sin_size))==-1)
{
perror("falied accept");
continue;
}
memset(buff, 0, MAXDATASIZE);
recvbytes = read(client_fd, buff, MAXDATASIZE);
sprintf(filepath, "/etc/nginx/url_rule/%s", buff);
if ((fp = fopen(filepath, "wb")) == NULL)
{
perror("fopen");
close(client_fd);
continue;
}
write(client_fd, "sendmsg", 7);
while(read(client_fd, buff, MAXDATASIZE))
{
if (!memcmp(buff, "end", 3))
{
fclose(fp);
break;
}
else
{
fprintf(fp, "%s", buff);
write(client_fd, "goon", 4);
}
}
//system("nginx -s reload");
char *Sptr = "nginx reload succ";
char *Eptr = "nginx reload error";
int ret;
ret = system("nginx -s reload");
printf("ret[%d]\n", ret);
if (ret != 0)
{
write(client_fd, Eptr, strlen(Eptr));
}
else
{
write(client_fd, Sptr, strlen(Sptr));
}
close(client_fd);
}
}
以前寫的:內容忘記了。不是很復雜你可以自己看!
❺ linux下socket 網路編程(客戶端向伺服器端發送文件) 求源代碼 大哥大姐幫幫忙 ,。。謝謝
源代碼奉上,流程圖。。。這個太簡單了,你自己看看。。。。。。。
//TCP
//伺服器端程序
#include< stdio.h >
#include< stdlib.h >
#include< windows.h >
#include< winsock.h >
#include< string.h >
#pragma comment( lib, "ws2_32.lib" )
#define PORT 2046
#define BACKLOG 10
#define TRUE 1
void main( void )
{
int iServerSock;
int iClientSock;
char *buf = "hello, world!\n";
struct sockaddr_in ServerAddr;
struct sockaddr_in ClientAddr;
int sin_size;
WSADATA WSAData;
if( WSAStartup( MAKEWORD( 1, 1 ), &WSAData ) )//初始化
{
printf( "initializationing error!\n" );
WSACleanup( );
exit( 0 );
}
if( ( iServerSock = socket( AF_INET, SOCK_STREAM, 0 ) ) == INVALID_SOCKET )
{
printf( "創建套接字失敗!\n" );
WSACleanup( );
exit( 0 );
}
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons( PORT );//監視的埠號
ServerAddr.sin_addr.s_addr = INADDR_ANY;//本地IP
memset( & ( ServerAddr.sin_zero ), 0, sizeof( ServerAddr.sin_zero ) );
if( bind( iServerSock, ( struct sockaddr * )&ServerAddr, sizeof( struct sockaddr ) ) == -1 )
{
printf( "bind調用失敗!\n" );
WSACleanup( );
exit( 0 );
}
if( listen( iServerSock, BACKLOG ) == -1 )
{
printf( "listen調用失敗!\n" );
WSACleanup( );
exit( 0 );
}
while( TRUE )
{
sin_size = sizeof( struct sockaddr_in );
iClientSock = accept( iServerSock, ( struct sockaddr * )&ClientAddr, &sin_size );
if( iClientSock == -1 )
{
printf( "accept調用失敗!\n" );
WSACleanup( );
exit( 0 );
}
printf( "伺服器連接到%s\n", inet_ntoa( ClientAddr.sin_addr ) );
if( send( iClientSock, buf, strlen( buf ), 0 ) == -1 )
{
printf( "send調用失敗!" );
closesocket( iClientSock );
WSACleanup( );
exit( 0 );
}
}
}
/////客戶端程序
#include< stdio.h >
#include< stdlib.h >
#include< windows.h >
#include< winsock.h >
#include< string.h >
#pragma comment( lib, "ws2_32.lib" )
#define PORT 2046
#define BACKLOG 10
#define TRUE 1
#define MAXDATASIZE 100
void main( void )
{
int iClientSock;
char buf[ MAXDATASIZE ];
struct sockaddr_in ServerAddr;
int numbytes;
// struct hostent *he;
WSADATA WSAData;
// int sin_size;
/* if( ( he = gethostbyname( "liuys" ) ) == NULL )
{
printf( "gethostbyname調用失敗!" );
WSACleanup( );
exit( 0 );
}
*/
if( WSAStartup( MAKEWORD( 1, 1 ), &WSAData ) )//初始化
{
printf( "initializationing error!\n" );
WSACleanup( );
exit( 0 );
}
if( ( iClientSock = socket( AF_INET, SOCK_STREAM, 0 ) ) == INVALID_SOCKET )
{
printf( "創建套接字失敗!\n" );
WSACleanup( );
exit( 0 );
}
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons( PORT );
// ServerAddr.sin_addr = *( ( struct in_addr * )he->h_addr );
ServerAddr.sin_addr.s_addr = inet_addr( "192.168.2.194" );//記得換IP
memset( &( ServerAddr.sin_zero ), 0, sizeof( ServerAddr.sin_zero ) );
if( connect( iClientSock, ( struct sockaddr * ) & ServerAddr, sizeof( struct sockaddr ) ) == -1 )
{
printf( "connect失敗!" );
WSACleanup( );
exit( 0 );
}
numbytes = recv( iClientSock, buf, MAXDATASIZE, 0 );
if( numbytes == -1 )
{
printf( "recv失敗!" );
WSACleanup( );
exit( 0 );
}
buf[ numbytes ] = '\0';
printf( "Received: %s", buf );
closesocket( iClientSock );
WSACleanup( );
}
/////UDP
//伺服器
#include< stdio.h >
#include< string.h >
#include< winsock.h >
#include< windows.h >
#pragma comment( lib, "ws2_32.lib" )
#define PORT 2046
#define BACKLOG 10
#define TRUE 1
#define MAXDATASIZE 1000
void main( void )
{
int iServerSock;
// int iClientSock;
int addr_len;
int numbytes;
char buf[ MAXDATASIZE ];
struct sockaddr_in ServerAddr;
struct sockaddr_in ClientAddr;
WSADATA WSAData;
if( WSAStartup( MAKEWORD( 1, 1 ), &WSAData ) )
{
printf( "initializationing error!\n" );
WSACleanup( );
exit( 0 );
}
iServerSock = socket( AF_INET, SOCK_DGRAM, 0 );
if( iServerSock == INVALID_SOCKET )
{
printf( "創建套接字失敗!\n" );
WSACleanup( );
exit( 0 );
}
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons( PORT );//監視的埠號
ServerAddr.sin_addr.s_addr = INADDR_ANY;//本地IP
memset( & ( ServerAddr.sin_zero ), 0, sizeof( ServerAddr.sin_zero ) );
if( bind( iServerSock, ( struct sockaddr * )&ServerAddr, sizeof( struct sockaddr ) ) == -1 )
{
printf( "bind調用失敗!\n" );
WSACleanup( );
exit( 0 );
}
addr_len = sizeof( struct sockaddr );
numbytes = recvfrom( iServerSock, buf, MAXDATASIZE, 0, ( struct sockaddr * ) & ClientAddr, &addr_len );
if( numbytes == -1 )
{
printf( "recvfrom調用失敗!\n" );
WSACleanup( );
exit( 0 );
}
printf( "got packet from %s\n", inet_ntoa( ClientAddr.sin_addr ) );
printf( "packet is %d bytes long\n", numbytes );
buf[ numbytes ] = '\0';
printf( "packet contains \"%s\"\n", buf );
closesocket( iServerSock );
WSACleanup( );
}
//客戶端
#include< stdio.h >
#include< stdlib.h >
#include< windows.h >
#include< winsock.h >
#include< string.h >
#pragma comment( lib, "ws2_32.lib" )
#define PORT 2046
#define MAXDATASIZE 100
void main( void )
{
int iClientSock;
struct sockaddr_in ServerAddr;
int numbytes;
char buf[ MAXDATASIZE ] = { 0 };
WSADATA WSAData;
if( WSAStartup( MAKEWORD( 1, 1 ), &WSAData ) )
{
printf( "initializationing error!\n" );
WSACleanup( );
exit( 0 );
}
if( ( iClientSock = socket( AF_INET, SOCK_DGRAM, 0 ) ) == -1 )
{
printf( "創建套接字失敗!\n" );
WSACleanup( );
exit( 0 );
}
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons( PORT );
ServerAddr.sin_addr.s_addr = inet_addr( "192.168.2.194" );//記得換IP
memset( &( ServerAddr.sin_zero ), 0, sizeof( ServerAddr.sin_zero ) );
numbytes = sendto( iClientSock, buf, strlen( buf ), 0, ( struct sockaddr * ) & ServerAddr, sizeof( struct sockaddr ) );
if( numbytes == -1 )
{
printf( "sendto調用失敗!\n" );
WSACleanup( );
exit( 0 );
}
printf( "sent %d bytes to %s\n", numbytes, inet_ntoa( ServerAddr.sin_addr ) );
closesocket( iClientSock );
WSACleanup( );
}