前言:
现在兄弟们对“java用socket发送报文”大约比较注意,同学们都想要知道一些“java用socket发送报文”的相关内容。那么小编也在网摘上网罗了一些有关“java用socket发送报文””的相关文章,希望各位老铁们能喜欢,姐妹们快快来了解一下吧!/*
linux 下发送和接收链路层广播报文
*/
#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netinet/ip.h>
#include<net/if.h>
#include<netpacket/packet.h>
#include<net/ethernet.h>
#include<arpa/inet.h>
#include<net/if_arp.h>
#define BUFFER_SIZE 1024*2
#define CFG_ETHN "eth1"
int main()
{
int socket,ret;
char buffer[BUFFER_SIZE];
struct sockaddr_ll dest_addr;
struct ifreq ifr;
//创建原始套接字
sockfd = socket(AF_PACKET, SOCK_RAM, htons(ETH_P_ALL));
if(sockfd <0)
{
perror("socket creation failed");
return 1;
}
//设置接口为混杂模式
strncpy(ifr, ifr_name, CFG_ETHN, IFNAMSIZ);
ret = setsockopt(sockfd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr));
if(ret < 0)
{
perror("setsockopt failed");
return 1;
}
int count = 0;
while(1)
{
//接收报文
memset(buffer, 0x0, BBUFFER_SIZE;
ret = recvfrom(sockfd, buffer, BUFFER_SIZE, 0 ,NULL, NULL);
if(ret<0)
{
perror("recvfrom failed");
close(sockfd);
return 1;
}
printf("%s receive len:%d\n", CFG_ETHN, ret);
count++;
printf("not 0 count++:%d\n", ret);
printf("Received broadcast message:len %ld",ret);
for(int i =0; i < ret; i++)
{
printf("%02x ", uffer[i]&0xff);
}
printf("\n\n");
close(sockfd);
return 0;
}
===============================
发送代码
int sockfd,ret;
char buffer[UFFER_SIZE];
struct sockadd_lldest_addr;
struct ifreq ifr;
memset(&dest_addr,0,sizeof(dest_addr));
dest_addr.ll_family = AF_PACKET;
.sll_protocol = htons(ETH_P_ALL;
.sll_ifindex = if_nametoindex(CFG_ETHN);
.sll_hatype = ARPHRD_ETHER;
.sll_pkttype = PACKET_ROADCAST;
.sll_halen = ETH_ALEN;
memset(dest_addr,sll_addr,0xff,ETH_ALEN);
sprintf(sendbuf,"strlen(sendbuff):%d",strlen(sendbuf));
memcpy(sendbuf,&strpktinfo,sizeof(STU_PTK_INFO);
ret = sendto(sockfd,senduff,60,0,(struct sockaddr*)&dest_addr,sizeof(dest_addr));
if(ret<0)
{
perror("sendto failed");
close(sockfd);
return1;
}
printf("sendroadcast message"\n);
for(int i =0; i < sizeof(STU_PKT_INFO); i++)
{
printf("%02x",senduf[i]&0xff);
}
printf("\n\n")
}
close(sockfd);
return 0;
}
}
标签: #java用socket发送报文