I once wanted to get THERMOCOUPLE DATA and by making HTTP request I put it on API
it worked flawlessly , here is the code for esp32:
// this example is public domain. enjoy! https://learn.adafruit.com/thermocouple/
#include "max6675.h"
#include <ArduinoJson.h>
#include <HTTPClient.h>
#include <WiFiMulti.h>
int thermoDO = 19;
int thermoCS = 23;
int thermoCLK = 5;
MAX6675 thermocouple(thermoCLK, thermoCS, thermoDO);
const char *AP_SSID = "ssid";
const char *AP_PWD = "pass";
WiFiMulti wifiMulti;
void setup() {
Serial.begin(9600);
delay(4000);
wifiMulti.addAP(AP_SSID, AP_PWD);
Serial.println("MAX6675 test");
// wait for MAX chip to stabilize
delay(500);
}
void loop() {
// basic readout test, just print the current temp
Serial.print("C = ");
Serial.println(thermocouple.readCelsius());
Serial.print("F = ");
Serial.println(thermocouple.readFahrenheit());
// For the MAX6675 to update, you must delay AT LEAST 250ms between reads!
delay(1000);
postDataToServer();
}
void postDataToServer() {
Serial.println("Posting JSON data to server...");
// Block until we are able to connect to the WiFi access point
if (wifiMulti.run() == WL_CONNECTED) {
HTTPClient http;
http.begin("https://retoolapi.dev/fyXalF/data/1");
http.addHeader("Content-Type", "application/json");
StaticJsonDocument<200> doc;
// Add values in the document
//
doc["temp1"] = thermocouple.readCelsius();
doc["temp2"] = thermocouple.readFahrenheit();
String requestBody;
serializeJson(doc, requestBody);
int httpResponseCode = http.PUT(requestBody);
if(httpResponseCode>0){
String response = http.getString();
Serial.println(httpResponseCode);
Serial.println(response);
}
else {
Serial.printf("Error occurred while sending HTTP POST");
}
}
}
now I'm trying to do it by esp8266.
so the code is basically the same , you have to put "ESP8266" before library names and for making http.begin() you have to pass a WiFiClient beside API address :
// this example is public domain. enjoy! https://learn.adafruit.com/thermocouple/
#include "max6675.h"
#include <ArduinoJson.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFiMulti.h>
#include <WiFiClientSecure.h>
int thermoDO = 19;
int thermoCS = 23;
int thermoCLK = 5;
MAX6675 thermocouple(thermoCLK, thermoCS, thermoDO);
const char *AP_SSID = "ssid";
const char *AP_PWD = "pass";
ESP8266WiFiMulti wifiMulti;
void setup() {
Serial.begin(9600);
delay(4000);
wifiMulti.addAP(AP_SSID, AP_PWD);
Serial.println("MAX6675 test");
// wait for MAX chip to stabilize
delay(500);
}
void loop() {
// basic readout test, just print the current temp
Serial.print("C = ");
Serial.println(thermocouple.readCelsius());
Serial.print("F = ");
Serial.println(thermocouple.readFahrenheit());
// For the MAX6675 to update, you must delay AT LEAST 250ms between reads!
delay(1000);
postDataToServer();
}
void postDataToServer() {
Serial.println("Posting JSON data to server...");
// Block until we are able to connect to the WiFi access point
if (wifiMulti.run() == WL_CONNECTED) {
WiFiClient client;
HTTPClient http;
http.begin(client,"https://retoolapi.dev/fyXalF/data/1");
http.addHeader("Content-Type", "application/json");
StaticJsonDocument<200> doc;
// Add values in the document
//
doc["temp1"] = thermocouple.readCelsius();
doc["temp2"] = thermocouple.readFahrenheit();
String requestBody;
serializeJson(doc, requestBody);
int httpResponseCode = http.PUT(requestBody);
if(httpResponseCode>0){
String response = http.getString();
Serial.println(httpResponseCode);
Serial.println(response);
}
else {
Serial.printf("Error occurred while sending HTTP POST");
}
}
}
it compiled but I got "bad request-400" and "The plain HTTP request was sent to HTTPS port" as a response .
I think the esp8266 library cant send https requests ...
any ideas how to solve this ?
PS : I also use #include <WiFiClientSecure.h>
WiFiClientSecure client;
HTTPClient http;
http.begin(client,"https://retoolapi.dev/0tvafA/data/1");
it's not working either : Error occurred while sending HTTP POSTC = 0.00
:(
Related
I am trying to connect NodeMCU with unity for my university project.
My nodemcu receives data (tested with a UDP test tool application). I will leave the code below.
But I have problems with Unity. I tried to find a simple example or something like that.
The code I found recently is simple enough, but it makes Unity freeze. I found it here and edited it a bit.
NodeMCU code in Arduino IDE
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
const char* ssid = "Epic SSID";
const char* password = "EpicPassword";
WiFiUDP Udp;
unsigned int port = 25666;
char packet[255];
IPAddress ip(192, 168, 43, 20);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
void setup()
{
Serial.begin(115200);
Serial.println();
WiFi.hostname("YVRB-01");
WiFi.config(ip, gateway, subnet);
Serial.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("Connection Successful");
Udp.begin(port);
Serial.printf("Listener started at IP %s, at port %d", WiFi.localIP().toString().c_str(), port);
}
void loop()
{
int packetSize = Udp.parsePacket();
if (packetSize)
{
Serial.printf("Received %d bytes from %s, port %d", packetSize, Udp.remoteIP().toString().c_str(), Udp.remotePort());
int len = Udp.read(packet, 255);
if (len > 0)
{
packet[len] = 0;
}
Serial.printf("UDP packet contents: %s", packet);
Serial.println();
}
Udp.beginPacket (Udp.remoteIP(), Udp.remotePort());
Udp.write("Epic message");
Udp.endPacket();
delay(300);
}
When it worked, I took off my shirt and ran too kitchen.
My code in Unity
/*
C# Network Programming
by Richard Blum
Publisher: Sybex
ISBN: 0782141765
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;
public class udpsend : MonoBehaviour
{
Socket server;
IPEndPoint ipep;
void Start()
{
byte[] data = new byte[1024];
ipep = new IPEndPoint(
IPAddress.Parse("192.162.43.209"), 25666);
server = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
string welcome = "I am connected";
data = Encoding.ASCII.GetBytes(welcome);
server.SendTo(data, data.Length, SocketFlags.None, ipep);
}
void Update()
{
string input, stringData;
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)sender;
byte[] data = new byte[1024];
int recv = server.ReceiveFrom(data, ref Remote);
Console.WriteLine("Message received from {0}:", Remote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
//while (true)
//{
// input = Console.ReadLine();
// if (input == "exit")
// break;
// server.SendTo(Encoding.ASCII.GetBytes(input), Remote);
// data = new byte[1024];
// recv = server.ReceiveFrom(data, ref Remote);
// stringData = Encoding.ASCII.GetString(data, 0, recv);
// Console.WriteLine(stringData);
//}
Console.WriteLine("Stopping client");
server.Close();
}
public void SendData(string message)
{
byte[] data = new byte[1024];
data = Encoding.ASCII.GetBytes(message);
server.SendTo(data, data.Length, SocketFlags.None, ipep);
}
}
I'm just saying that I don't fully understand, but I edited a little bit.
Any fixes or code examples will be appreciated. I just want a method that I can call like SendData("Never gonna give you up!").
I can now transfer information from the Unity app to NodeMCU and from NodeMCU to Unity!
All the code is below.
I used the code and edited the a bit.
To receive data, I used this code right here.
To send information, I used this code and like a "mash up" this code together to create one program that can send and receive.
The reason I have done this is that there were a conflict, because there were one client and multiple codes trying to access it.
For Node MCU I used this code which is pretty much the same as I wrote in question above.
I also made manager code using which I can send message and do other stuff.
It is also important to close all the ports or else Unity will freeze (a very annoying thing).
Nodemcu code in the Arduino IDE:
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
const char* ssid = "YVRB";
const char* password = "YGreater";
WiFiUDP Udp;
unsigned int port = 25666;
char packet[255];
IPAddress ip(192, 168, 43, 20);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
void setup()
{
Serial.begin(115200);
Serial.println();
WiFi.hostname("YVRB-01");
WiFi.config(ip, gateway, subnet);
Serial.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("Connection Successful");
Udp.begin(port);
Serial.printf("Listener started at IP %s, at port %d", WiFi.localIP().toString().c_str(), port);
Serial.println();
}
void loop()
{
int packetSize = Udp.parsePacket();
if (packetSize)
{
Serial.printf("Received %d bytes from %s, port %d", packetSize, Udp.remoteIP().toString().c_str(), Udp.remotePort());
int len = Udp.read(packet, 255);
if (len > 0)
{
packet[len] = 0;
}
Serial.printf("UDP packet contents: %s", packet);
Serial.println();
}
Udp.beginPacket (Udp.remoteIP(), Udp.remotePort());
Udp.write("Important data");
Udp.endPacket();
delay(300);
}
File UDPSend.cs code which receives as well:
// Inspired by this thread: https://forum.unity.com/threads/simple-udp-implementation-send-read-via-mono-c.15900/
// Thanks OP la1n
// Thanks MattijsKneppers for letting me know that I also need to lock my queue while enqueuing
// Adapted during projects according to my needs
using UnityEngine;
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class UDPSend
{
public string IP { get; private set; }
public int sourcePort { get; private set; } // Sometimes we need to define the source port, since some devices only accept messages coming from a predefined sourceport.
public int remotePort { get; private set; }
IPEndPoint remoteEndPoint;
Thread receiveThread;
// udpclient object
UdpClient client;
// public
// public string IP = "127.0.0.1"; default local
public int port = 25666; // define > init
// Information
public string lastReceivedUDPPacket = "";
public string allReceivedUDPPackets = ""; // Clean up this from time to time!
public bool newdatahereboys = false;
public void init(string IPAdress, int RemotePort, int SourcePort = -1) // If sourceport is not set, its being chosen randomly by the system
{
IP = IPAdress;
sourcePort = SourcePort;
remotePort = RemotePort;
remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), remotePort);
if (sourcePort <= -1)
{
client = new UdpClient();
Debug.Log("Sending to " + IP + ": " + remotePort);
}
else
{
client = new UdpClient(sourcePort);
Debug.Log("Sending to " + IP + ": " + remotePort + " from Source Port: " + sourcePort);
}
receiveThread = new Thread(
new ThreadStart(ReceiveData));
receiveThread.IsBackground = true;
receiveThread.Start();
}
private void ReceiveData()
{
//client = sender.client;
while (true)
{
try
{
// Bytes empfangen.
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
byte[] data = client.Receive(ref anyIP);
// Bytes mit der UTF8-Kodierung in das Textformat kodieren.
string text = Encoding.UTF8.GetString(data);
// Den abgerufenen Text anzeigen.
Debug.Log(text);
newdatahereboys = true;
//PlayerPrefs.SetString("ReceivedData", text);
// Latest UDPpacket
lastReceivedUDPPacket = text;
// ....
allReceivedUDPPackets = allReceivedUDPPackets + text;
}
catch (Exception err)
{
Debug.Log(err.ToString());
}
}
}
// sendData in different ways. Can be extended accordingly
public void sendString(string message)
{
try
{
byte[] data = Encoding.UTF8.GetBytes(message);
client.Send(data, data.Length, remoteEndPoint);
}
catch (Exception err)
{
Debug.Log(err.ToString());
}
}
public void sendInt32(Int32 myInt)
{
try
{
byte[] data = BitConverter.GetBytes(myInt);
client.Send(data, data.Length, remoteEndPoint);
}
catch (Exception err)
{
Debug.Log(err.ToString());
}
}
public void sendInt32Array(Int32[] myInts)
{
try
{
byte[] data = new byte[myInts.Length * sizeof(Int32)];
Buffer.BlockCopy(myInts, 0, data, 0, data.Length);
client.Send(data, data.Length, remoteEndPoint);
}
catch (Exception err)
{
Debug.Log(err.ToString());
}
}
public void sendInt16Array(Int16[] myInts)
{
try
{
byte[] data = new byte[myInts.Length * sizeof(Int16)];
Buffer.BlockCopy(myInts, 0, data, 0, data.Length);
client.Send(data, data.Length, remoteEndPoint);
}
catch (Exception err)
{
Debug.Log(err.ToString());
}
}
public string getLatestUDPPacket()
{
allReceivedUDPPackets = "";
return lastReceivedUDPPacket;
}
public void ClosePorts()
{
Debug.Log("closing receiving UDP on port: " + port);
if (receiveThread != null)
receiveThread.Abort();
client.Close();
}
}
File manager.cs:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class manager : MonoBehaviour {
public int Remoteport = 25666;
public UDPSend sender = new UDPSend();
public string datafromnode;
void Start()
{
sender.init("192.168.43.209", Remoteport, 25666);
sender.sendString("Hello from Start. " + Time.realtimeSinceStartup);
Application.targetFrameRate = 60;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyUp(KeyCode.Return))
sender.sendString("This should be delivered");
if (sender.newdatahereboys)
{
datafromnode = sender.getLatestUDPPacket();
}
}
public void OnDisable()
{
sender.ClosePorts();
}
public void OnApplicationQuit()
{
sender.ClosePorts();
}
}
Success! See justlookatem.
I am working on an application for the HoloLens (1) based on Unity. I am trying to send data via TCP from a Qt-based application (Windows) to the HoloLens. Wireshark shows, that my test package is correctly sent and acknowledged by the HoloLens. The data starts with four bytes containing the length of the message, which starts right after those four bytes. In the following code, first, the four bytes are trying to be received, and afterwards, the message itself.
After executing the code for connecting and sending the data in the client application, StreamSocketListener_ConnectionReceived() is called on the HoloLens. In the next Update() call, ReadTcpData() is called. Now, execution 'stops' at the first call to
tcpMessageSizeBuffer[tcpMessageSizeBytesRead++] = (byte)stream.ReadByte();
At least the debugger jumps out of the code when I try to step over the line. There is no exception caught in the catch block.
I was expecting that the EndOfStream property of StreamReader would be false if there is nothing to read, and consequently, I would receive a valid byte from the stream when calling ReadByte when it was true. I have no clue what goes wrong here. Any hints would be greatly appreciated.
using System;
using System.IO;
using UnityEngine;
#if UNITY_WINRT && !UNITY_EDITOR
using Windows.Networking.Sockets;
using Windows.Networking;
using Windows.Networking.Connectivity;
using Windows.Storage.Streams;
using System.Runtime.InteropServices.WindowsRuntime;
#endif
public class NetworkManager : MonoBehaviour
{
public int tcpPort;
#if UNITY_WINRT && !UNITY_EDITOR
private StreamSocketListener streamSocketListener;
private StreamReader tcpStreamReader = null;
private StreamSocketListenerConnectionReceivedEventArgs connectionArgs;
private DatagramSocket datagramSocket;
private MemoryStream pendingDatagramSocketStream;
#endif
private UInt32 tcpMessageSizeByteCount;
private UInt32 tcpMessageSizeBytesRead;
private byte[] tcpMessageSizeBuffer;
private bool tcpMessageSizeReceived;
private UInt32 tcpMessageByteCount;
private UInt32 tcpMessageBytesRead;
private byte[] tcpMessageBuffer;
// Use this for initialization
void Start()
{
Application.runInBackground = true;
ResetTcpConnection();
}
public void ResetTcpConnection()
{
#if UNITY_WINRT && !UNITY_EDITOR
ResetTcpRead();
if (streamSocketListener != null)
{
tcpStreamReader.Dispose();
tcpStreamReader = null;
connectionArgs = null;
streamSocketListener.Dispose();
streamSocketListener = null;
}
streamSocketListener = new StreamSocketListener();
streamSocketListener.ConnectionReceived += this.StreamSocketListener_ConnectionReceived;
streamSocketListener.BindServiceNameAsync(tcpPort.ToString());
#endif
}
#if UNITY_WINRT && !UNITY_EDITOR
// Process the client connection.
private async void StreamSocketListener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
connectionArgs = args; // Keep this alive
tcpStreamReader = new StreamReader(connectionArgs.Socket.InputStream.AsStreamForRead());
}
#endif
// Update is called once per frame
void Update()
{
#if UNITY_WINRT && !UNITY_EDITOR
if (tcpStreamReader != null && !tcpStreamReader.EndOfStream)
{
Stream stream = tcpStreamReader.BaseStream;
ReadTcpData(ref stream);
}
#endif
}
private void ResetTcpRead()
{
tcpMessageSizeByteCount = sizeof(UInt32);
tcpMessageSizeBytesRead = 0;
tcpMessageSizeBuffer = new byte[tcpMessageSizeByteCount];
tcpMessageSizeReceived = false;
tcpMessageByteCount = 0;
tcpMessageBytesRead = 0;
tcpMessageBuffer = null;
}
private void ReadTcpData(ref Stream stream)
{
try
{
if (!tcpMessageSizeReceived)
{
#if UNITY_WINRT && !UNITY_EDITOR
while(tcpMessageSizeBytesRead < tcpMessageSizeByteCount && !tcpStreamReader.EndOfStream)
{
tcpMessageSizeBuffer[tcpMessageSizeBytesRead++] = (byte)stream.ReadByte();
}
if(tcpMessageSizeBytesRead == tcpMessageSizeByteCount)
{
tcpMessageByteCount = BitConverter.ToUInt32(tcpMessageSizeBuffer, 0);
}
#endif
if (tcpMessageByteCount > 0)
{
tcpMessageBuffer = new byte[tcpMessageByteCount];
tcpMessageSizeReceived = true;
}
}
else
{
// Read the message
int bytesToRead = (int)(tcpMessageByteCount - tcpMessageBytesRead);
bytesToRead = bytesToRead > 10000 ? 10000 : bytesToRead;
int bytesRead = stream.Read(tcpMessageBuffer, (int)tcpMessageBytesRead, bytesToRead);
tcpMessageBytesRead += (uint)bytesRead;
// Did we finish reading the message?
if (tcpMessageBytesRead >= tcpMessageByteCount)
{
ResetTcpRead();
}
}
}
catch (Exception e)
{
throw e;
}
}
}
Found the problem - I have to use BinaryReader and replace the code reading the length of the message such:
while(tcpMessageSizeBytesRead < tcpMessageSizeByteCount)
{
tcpMessageSizeBuffer[tcpMessageSizeBytesRead++] = (byte)binaryReader.ReadByte();
}
For the sake of consistency, also the part of the code actually reading the message can be adapted to use BinaryReader.
I don't get it, my friend and I are developing an API and our WebSocket services works, but not the mobile side.. I tried with a couple of clients, on the web, our echo messaging and everything works.
The thing is, I mean, the things seem like the socket is mono-directional. I tried the example of https://github.com/rdavisau/sockets-for-pcl#a-tcp-client:
var address = "127.0.0.1";
var port = 11000;
var r = new Random();
var client = new TcpSocketClient();
await client.ConnectAsync(address, port);
// we're connected!
for (int i = 0; i<5; i++)
{
// write to the 'WriteStream' property of the socket client to send data
var nextByte = (byte) r.Next(0,254);
client.WriteStream.WriteByte(nextByte);
await client.WriteStream.FlushAsync();
// wait a little before sending the next bit of data
await Task.Delay(TimeSpan.FromMilliseconds(500));
}
await client.DisconnectAsync();
First, after I get connected with this :
public async void ConnectSocketToAPIAsync()
{
SocketClient = new TcpSocketClient();
await SocketClient.ConnectAsync("my.ws.service", 4242);
ActiveSocketExchange();
}
public async void ActiveSocketExchange()
{
var bytesRead = -1;
var buf = new byte[1];
while (bytesRead != 0)
{
bytesRead = await SocketClient.ReadStream.ReadAsync(buf, 0, 1);
if (bytesRead > 0)
MessagingCenter.Send((App)Current, SOCKET_Message, System.Text.Encoding.UTF8.GetString(buf, 0, bytesRead));
}
}
Everything's fine, my TcpClient is well initialized (even the web-link becomes the http's API addr)
From my page view, when I'm done writing my text, I'm pressing the done button of the keyboard and this code is called:
private void InitSocketPart()
{
MessagingCenter.Subscribe<App, string>((App)Application.Current, App.SOCKET_Message, (sender, text) =>
{
SocketResponseText = text;
});
}
private async void OnTextCompleted(object sender, EventArgs ea)
{
var bytes = Encoding.UTF8.GetBytes(TextToSend);
try {
if (App.SocketClient.WriteStream.CanRead)
Debug.WriteLine("canRead");
if (App.SocketClient.WriteStream.CanWrite)
Debug.WriteLine("canWrite");
App.SocketClient.WriteStream.Write(bytes, 0, TextToSend.Length);
App.SocketClient.WriteStream.Flush();
} catch (Exception e)
{
Debug.WriteLine(e);
}
}
So now CanWrite && CanRead are true, but nothing at all happens, even with the use of Async methods... Why so? I don't get it..
The use of messaging center is just to have only one point of incoming message. I'm using it for other things and it works perfectly :)
Thank for any help..
I'm using jnetpcap to analyzing packet. I want to get html web page source code.
However, when I use html.page() to get source code I get some messy code which look like binary code. Can anyone help me? How to solve it?
Not a jnetpcap expert, but I have been using this class for a while and it seems to work. It actually gets many HTTP fields, including its payload.
package br.com.mvalle.ids.sniffer;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.jnetpcap.Pcap;
import org.jnetpcap.PcapIf;
import org.jnetpcap.packet.PcapPacket;
import org.jnetpcap.packet.PcapPacketHandler;
import org.jnetpcap.packet.format.FormatUtils;
import org.jnetpcap.protocol.network.Ip4;
import org.jnetpcap.protocol.tcpip.Http;
import org.jnetpcap.protocol.tcpip.Tcp;
public class Sniffer {
private List<PcapIf> alldevs = new ArrayList<PcapIf>(); // Will be filled with NICs
private StringBuilder errbuf = new StringBuilder(); // For any error msgs
private PcapIf selectedDevice;
private Pcap pcap;
private PcapPacketHandler<String> jpacketHandler;
public Sniffer(){
listDevices();
selectedDevice = selectDevice(1);
openDevice(selectedDevice);
packetHandler();
capturePackets();
}
public void listDevices(){
int r = Pcap.findAllDevs(alldevs, errbuf);
if (r == Pcap.NOT_OK || alldevs.isEmpty()) {
System.err.printf("Can't read list of devices, error is %s", errbuf.toString());
return;
}
System.out.println("Network devices found:");
int i = 0;
for (PcapIf device : alldevs) {
String description =
(device.getDescription() != null) ? device.getDescription()
: "No description available";
System.out.printf("#%d: %s [%s]\n", i++, device.getName(), description);
}
}
private PcapIf selectDevice(int deviceId){
PcapIf device = alldevs.get(1); // We know we have atleast 1 device (parameter changed from 0 to 1)
System.out
.printf("\nChoosing '%s' on your behalf:\n",
(device.getDescription() != null) ? device.getDescription()
: device.getName());
return device;
}
private void openDevice (PcapIf device){
int snaplen = 64 * 1024; // Capture all packets, no trucation
int flags = Pcap.MODE_PROMISCUOUS; // capture all packets
int timeout = 10 * 1000; // 10 seconds in millis
pcap =
Pcap.openLive(device.getName(), snaplen, flags, timeout, errbuf);
if (pcap == null) {
System.err.printf("Error while opening device for capture: "
+ errbuf.toString());
return;
}
}
private void packetHandler(){
jpacketHandler = new PcapPacketHandler<String>() {
Http httpheader = new Http();
public void nextPacket(PcapPacket packet, String user) {
if(packet.hasHeader(httpheader)){
System.out.println(httpheader.toString());
if(httpheader.hasPayload()){
System.out.println("HTTP payload: (string length is "
+new String(httpheader.getPayload()).length()+")");
System.out.println(new String(httpheader.getPayload()));
System.out.println("HTTP truncated? "
+httpheader.isPayloadTruncated());
}
//System.out.println(packet.toString());
}}
};
}
private void capturePackets(){
pcap.loop(pcap.LOOP_INFINITE , jpacketHandler, "Received Packet");
pcap.close();
}
}
Hope it helps.
I am new to VC++ and programming.
I have to write code to send a email in VC++.
How do I go about it? Please help!!
Here's how I do it with the ATL classes. I think you need one of the paid versions of VC++ to get ATL. You will need the name of your email server.
CSMTPConnection smtp;
if (!smtp.Connect(m_strEmailServer))
return false;
// start generating the email message; remember to call CoInitialize somewhere in the app before this
CMimeMessage msg;
msg.SetSubject(m_strSubject);
msg.SetSender(m_strSender);
// repeat the following as necessary
msg.AddRecipient(strSingleRecipient);
msg.AddText(m_strBody);
if (!smtp.SendMessage(msg))
return false;
return true;
Can your software require MAPI? That's an interface that provides a fairly simple interface to whatever the user's installed as default email program is.
If so, then you can use something like the following:
/////////////////////////////////////////////////////////
// CMapiSendMessage
// Allows for simplified message generation and transmission using Simple MAPI
class CMapiSendMessage
{
public:
// constant data
enum RecipientType { FROM = MAPI_ORIG, TO = MAPI_TO, CC = MAPI_CC, BCC = MAPI_BCC };
// ctors
CMapiSendMessage() { }
// accessors
CString GetSubject() const { return m_subject; }
CString & GetMessage() { return m_message; }
const CString & GetMessage() const { return m_message; }
// setters
void AddRecipient(RecipientType type, const CStringA & strName, const CStringA & strAddress = "")
{
m_recipients.push_back(Recipient(type, strName, strAddress));
}
void SetSubject(const CString & strSubject)
{
m_subject = strSubject;
}
void SetMessage(const CString & strMessage)
{
m_message = strMessage;
}
void AddAttachment(const CFilename & filename)
{
m_attachments.push_back(filename.cstring());
}
// actions
ULONG Send(bool bShowDialog, HWND hwndParent); // send this message, show or don't show the user the message dialog
// returns SUCCESS_SUCCESS if all went well
// returns MAPI_USER_ABORT if user aborted the send
// returns MAPI_E_LOGIN_FAILURE if unable to login to MAPI service (user login failed)
ULONG AfxSend(bool bShowDialog, bool bShowError); // send message with special processing for an MFC application
// set bShowError if you wish to automatically show standard MFC error messages if the send message failed
protected:
// types
struct Recipient
{
RecipientType type;
CStringA name;
CStringA address;
Recipient(RecipientType _type, const CStringA & _name, const CStringA & _address = "") :
type(_type), name(_name), address(_address)
{
}
// force default ctor to set type to zero (not random)
Recipient() : type(FROM) { }
};
typedef std::vector<Recipient> RecipientVector;
typedef std::vector<CString> AttachmentVector;
CMailAPI32 m_api; // MAPI interface
RecipientVector m_recipients; // recipients (TO:, CC:, and BCC:)
CString m_subject; // message subject
CString m_message; // message body text
AttachmentVector m_attachments; // file attachments
};
And the CPP half:
typedef std::vector<CMapiRecipDesc> MapiRecipDescVector;
typedef std::vector<CMapiFileDesc> MapiFileDescVector;
//////////////////////////////////////////////////////////////////////
// CMailAPI32
//////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
// CMapiSendMessage
ULONG CMapiSendMessage::Send(bool bShowDialog, HWND hwndParent) // send, show user interface - let them edit the message and have final choice in send/cancel
{
// save the cwd
CPathname cwd(CPathname::GetCurrent());
// build the recipients array
const size_t total_recipients = m_recipients.size();
MapiRecipDescVector recipients(total_recipients);
for (size_t i = 0; i < total_recipients; ++i)
{
CMapiRecipDesc recipient;
recipient.ulReserved = 0L;
recipient.ulRecipClass = m_recipients[i].type;
recipient.lpszName = const_cast<LPSTR>(GetPtrOrNull(m_recipients[i].name));
recipient.lpszAddress = const_cast<LPSTR>(GetPtrOrNull(m_recipients[i].address));
recipient.ulEIDSize = 0;
recipient.lpEntryID = NULL;
recipients[i] = recipient;
}
// build attachments array
const size_t total_attachments = m_attachments.size();
MapiFileDescVector attachments(total_attachments);
for (size_t j = 0; j < total_attachments; ++j)
{
CFilename filename(m_attachments[j]);
if (!filename.Exists())
ThrowLabeledException(FString(_T("File does not exist: %s"), filename.c_str()));
// get the fully specified path
size_t size = filename.cstring().GetLength() + 1;
attachments[j].lpszPathName = new char[size];
#ifdef _UNICODE
_wcstombsz(attachments[j].lpszPathName, filename, size);
#else
lstrcpy(attachments[j].lpszPathName, filename);
#endif
// build an appropriate title for the attachment
CString strTitle = filename.GetFullName();
size = strTitle.GetLength() + 1;
attachments[j].lpszFileName = new char[size];
#ifdef _UNICODE
_wcstombsz(attachments[j].lpszFileName, strTitle, size);
#else
lstrcpy(attachments[j].lpszFileName, strTitle);
#endif
// attachment not embedded in the mapi_msg text;
attachments[j].nPosition = (ULONG)-1;
}
// prepare the mapi_msg
MapiMessage mapi_msg =
{
0, // reserved, must be 0
(LPSTR)GetPtrOrNull(m_subject), // subject
(LPSTR)GetPtrOrNull(m_message), // body
NULL, // NULL = interpersonal mapi_msg
NULL, // no date; MAPISendMail ignores it
NULL, // no conversation ID
0L, // no flags, MAPISendMail ignores it
NULL, // no originator, this is ignored too
total_recipients, // no. recipients
total_recipients ? &recipients[0] : NULL, // array of recipients
total_attachments, // no. attachments
total_attachments ? &attachments[0] : NULL // array of attachments
};
// send mail
FLAGS flags = MAPI_LOGON_UI;
BitSetIf(flags, MAPI_DIALOG, bShowDialog);
ULONG nError = m_api.SendMail(
NULL, // temporary session
(ULONG)hwndParent,
&mapi_msg,
flags,
0
);
// delete the attachment filenames
for (int k = total_attachments; k ; --k)
{
delete [] attachments[k-1].lpszPathName;
delete [] attachments[k-1].lpszFileName;
}
// restore CWD
cwd.SetCurrent();
// indicate if we succeeded or not
return nError;
}
ULONG CMapiSendMessage::AfxSend(bool bShowDialog, bool bReportError)
{
// prepare for modal dialog box
AfxGetApp()->EnableModeless(FALSE);
HWND hWndTop;
CWnd * pParentWnd = CWnd::GetSafeOwner(NULL, &hWndTop);
// some extra precautions are required to use MAPISendMail as it
// tends to enable the parent window in between dialogs (after
// the login dialog, but before the send note dialog).
pParentWnd->SetCapture();
::SetFocus(NULL);
pParentWnd->m_nFlags |= WF_STAYDISABLED;
// attempt to send the message
ULONG nError = Send(bShowDialog, pParentWnd->GetSafeHwnd());
// display error to user
if (nError != SUCCESS_SUCCESS &&
nError != MAPI_USER_ABORT &&
nError != MAPI_E_LOGIN_FAILURE)
{
AfxMessageBox(AFX_IDP_FAILED_MAPI_SEND);
}
// after returning from the MAPISendMail call, the window must
// be re-enabled and focus returned to the frame to undo the workaround
// done before the MAPI call.
::ReleaseCapture();
pParentWnd->m_nFlags &= ~WF_STAYDISABLED;
pParentWnd->EnableWindow(TRUE);
::SetActiveWindow(NULL);
pParentWnd->SetActiveWindow();
pParentWnd->SetFocus();
if (hWndTop != NULL)
::EnableWindow(hWndTop, TRUE);
AfxGetApp()->EnableModeless(TRUE);
// report success or not
return nError;
}
This is from my codebase - and I'm not making an effort to unravel it from my own libraries. But you should be able to "fill in the blanks".
Good luck!