Reputation: 343
Hi guys I'am trying to write IP Spoofing featured packetsender shared library for SIP application with JNI usage, When I tried to Run application and invoked native methods there wasn't any problem in the beginnings but after a time I think memory leak occured with no trace and crashed the JVM, my C is code (below) is higly influenced by this and here is my Method which I invoked with JNI can any one help me to find the leak?
int send_message(const char * sip_msg, const char * dest_ip, int dest_port, const char * spoofed_ip, unsigned int source_port){
unsigned int source_ip = 0;
srand(time(0));
if(source_port == 0){
source_port = rand() % 65535;
}
//unsigned int source_port = 0;
struct ip *ip;
struct udphdr *udp;
unsigned char packet[65535];
int len;
unsigned int msg_len =strlen(sip_msg);
struct sockaddr_in serv_addr;
int sockfd;
if ((sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) {
printf("\n Error : Could not create socket \n");
return 1;
}
const int on = 1;
if (setsockopt(sockfd, IPPROTO_IP, IP_HDRINCL, &on, sizeof(on)) == -1) {
perror("\n Error : Set Sock Opt \n");
return 1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(dest_port);
serv_addr.sin_addr.s_addr = inet_addr(dest_ip);
len = sizeof(struct ip) + sizeof(struct udphdr) + msg_len;
if (len > sizeof(packet)) {
printf("Failed to send1!\n");
return -2;
}
ip = (struct ip*) packet;
udp = (struct udphdr *) (packet + sizeof(struct ip));
memcpy(packet+sizeof(struct ip)+sizeof(struct udphdr),sip_msg,msg_len);
ip->ip_v = 4;
ip->ip_hl = sizeof(struct ip) / 4; // no options
ip->ip_tos = 0;
ip->ip_len = htons(len);
ip->ip_id = 23;
ip->ip_off = 0;
ip->ip_ttl = 69;
ip->ip_p = 17;
ip->ip_src.s_addr = inet_addr(spoofed_ip);
ip->ip_dst.s_addr = inet_addr(dest_ip);
ip->ip_sum = checksum((unsigned char *) ip, sizeof(struct ip));
/*if (source_port == 0) {
source_port = 5060;
}*/
udp->source = htons(source_port);
udp->dest = serv_addr.sin_port;
udp->len = htons((unsigned short) sizeof(struct udphdr) + msg_len);
udp->check = 0;
if (sendto(sockfd, packet, len, 0, (struct sockaddr *) (&serv_addr),
sizeof(struct sockaddr_in)) == -1) {
return -2;
printf("Failed to send!\n");
}
close(sockfd);
return 0;}
Upvotes: 2
Views: 283
Reputation: 4314
Yes, I can find a leak, not necessarily the leak.
Consider what happens if e.g. sendto
fails. The socket has been opened with socket()
, but you are not closing it. You really need to close
the socket for all code paths that can be taken. This, btw, is a case where the use of a goto
might be a good idea.
Upvotes: 1