易网时代-编程资源站
Welcome
微信登录
编程资源
图片资源库
蚂蚁家优选
PDF转换器
软件资源
软件开发
、
小程序制作
、
系统集成与运维
、
空间租用
、
硬件开发
、
视频监控
、
技术咨询与支持
——联系电话:0311-88999002/88999003
首页
/
操作系统
/
Linux
/
Linux向Windows通信C源代码
/*linux端*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#define MYPORT 3333
#define BACKLOG 10
void
main()
{
int
sockfd, new_fd;
struct
sockaddr_in my_addr;
struct
sockaddr_in their_addr;
int
sin_size;
if
((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror(
"socket"
);
exit(1);
}
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(MYPORT);
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
bzero(&(my_addr.sin_zero),0);
if
(bind(sockfd, (
struct
sockaddr *)&my_addr,
sizeof
(
struct
sockaddr))== -1) {
perror(
"bind"
);
exit(1);
}
if
(listen(sockfd, BACKLOG) == -1) {
perror(
"listen"
);
exit(1);
}
while
(1) {
sin_size =
sizeof
(
struct
sockaddr_in);
if
((new_fd = accept(sockfd, (
struct
sockaddr *)&their_addr,&sin_size)) == -1) {
printf(
"accept failure... "
);
perror(
"accept"
);
continue
;
}
//printf("server: got connection from %sn",inet_ntoa(their_addr.sin_addr));
if
(!fork()) {
if
(send(new_fd,
"Hello, world!n"
, 14, 0) == -1)
perror(
"send"
);
close(new_fd);
exit(0);
}
close(new_fd);
while
(waitpid(-1,NULL,WNOHANG) > 0);
}
}
/*windows 端*/
#include<Winsock2.h>
#include<stdio.h>
#pragma comment(lib,"ws2_32.lib")
void
main()
{
int
i;
char
recvBuffer[255];
WORD
wVersionRequested;
//typedef unsigned short WORD; 2字节
WSADATA wsaData;
//WSADATA 包含了Windows Socket执行的信息。
int
err;
wVersionRequested =MAKEWORD(1,1);
//这个宏创建一个被指定变量连接而成的WORD变量。返回一个WORD变量。
//第一个是socket库版本,第二个是取得的版本号。
err=WSAStartup(wVersionRequested,&wsaData);
//return 0 if successful
if
(err!=0){
printf(
"Call WSAStart ERROR!"
);
exit(1);
}
//终止对WinSock库的使用
SOCKET SocketClient=socket(AF_INET,SOCK_STREAM,0);
//0表示让系统自己选择协议
//定义地址结构体//填入服务器端的ip地址和端口号
SOCKADDR_IN addrSrv;
//转换为TCP/IP network byte order //32bit
addrSrv.sin_addr.S_un.S_addr=inet_addr(
"192.168.2.14"
);
//192.168.0.111ip 192.168.0.130
addrSrv.sin_family=AF_INET;
//family address
addrSrv.sin_port=htons(3333);
//16bit端口号
printf(
"Connect to server... "
);
i=connect(SocketClient,(sockaddr *)&addrSrv,
sizeof
(SOCKADDR_IN));
//指向要建立连接的数据结构
if
(i<0){
printf(
"%i "
,WSAGetLastError());
printf(
"连接到192.168.0.130:25000错误!"
);
exit(1);
}
recv(SocketClient,recvBuffer,255,0);
printf(
"%s "
,recvBuffer);
//send(socketClient,recvBuffer,20,0);
closesocket(SocketClient);
WSACleanup();
return
;
}
收藏该网址
版权所有©石家庄振强科技有限公司2024
冀ICP备08103738号-5
网站地图