我想通过c程序从以太网端口访问可用数据。 所以任何人都可以帮我提供任何简单的“C”源代码,用于从以太网端口获取数据。
由于
答案 0 :(得分:2)
我刚创建了2个程序来显示使用套接字与客户端/服务器通信的最低要求。您可以谷歌搜索每个功能,以了解他们的原型及其工作原理。
这是:
/*
Program: minser.c
Author: Dr Beco, 2011-04-03
Objective:
show a minimum server program that can
create a socket, accept a client, read a byte, write a byte, disconnect
*/
#include <stdio.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/un.h>
#define BUFFER 2
int main(void)
{
printf("Configuring environment... ");
int p = 3333; // port
char data[BUFFER];
struct sockaddr_in dir;
struct sockaddr client;
socklen_t long_client;
int id, idReuse=1, son, aux;
memset(&dir,0,sizeof(dir));
dir.sin_port = p;
dir.sin_family = AF_INET;
dir.sin_addr.s_addr = INADDR_ANY;
printf("done!\n");
printf("Creating socket... ");
id = socket(AF_INET, SOCK_STREAM, 0);
if (id == -1)
return -1;
printf("done!\n");
printf("Configuring socket... ");
if(setsockopt(id,SOL_SOCKET,SO_REUSEADDR,&idReuse,sizeof(idReuse))==-1)
return -1;
printf("done!\n");
printf("Binding... ");
if(bind(id, (struct sockaddr *)&dir, sizeof(dir)) == -1)
{
close (id);
return -1;
}
printf("done!\n");
printf("Listening... ");
if (listen(id , 1) == -1)
{
close(id);
return -1;
}
printf("done!\n");
printf("Accepting... ");
long_client = sizeof (client);
son = accept(id, &client, &long_client);
if (son == -1)
return -1;
printf("done!\n");
printf("Reading... ");
aux = read(son, data , 1);
if(aux!=1)
return -1;
printf("\"%c\" ", data[0]);
printf("done!\n");
printf("Writing \"S\"... ");
aux = send(son, "S", 1, MSG_NOSIGNAL);
if(aux < 0)
return -1;
printf("done!\n");
return 0;
}
/*
Program: mincli.c
Author: Dr Beco, 2011-04-03
Objective:
show a minimum client program that can
connect to a network, write a byte, read a byte, disconnect
*/
#include <stdio.h>
#include <unistd.h>
#include <netinet/in.h>
#include <netdb.h>
#define BUFFER 2
int main(void)
{
printf("Configuring environment... ");
char data[BUFFER];
const char *host_server="localhost";
struct sockaddr_in dir;
struct hostent *host;
int aux, id, p=3333; //port
dir.sin_port = p;
dir.sin_family = AF_INET;
host = gethostbyname(host_server);
if(host == NULL)
return -1;
dir.sin_addr.s_addr = ((struct in_addr *)(host->h_addr))->s_addr;
printf("done!\n");
printf("Creating socket... ");
id = socket(AF_INET, SOCK_STREAM, 0);
if(id == -1)
return -1;
printf("done!\n");
printf("Connecting... ");
if(connect(id, (struct sockaddr *)&dir, sizeof(dir)) == -1)
return -1;
printf("done!\n");
printf("Writing \"C\"... ");
aux = send(id, "C", 1, MSG_NOSIGNAL);
if(aux < 0)
return -1;
printf("done!\n");
printf("Reading... ");
aux = read(id, data , 1);
if(aux!=1)
return -1;
printf("\"%c\"", data[0]);
printf(" done!\n");
return 0;
}
保重, 贝乔
答案 1 :(得分:1)
您可以使用recv()
功能。