How to use android phone for SMS Sending app in C#? - c#

I am trying to develop a C# application that will be able to send SMS only through GSM Modem. When we connect a GSM Modem to our laptop/PC then we have to check the Port of that modem from Device manager > Modem > Port. But in this case, I want to connect my android phone as a GSM Modem with my laptop and trying to use the port number of my connected mobile phone but it is not connecting as a modem. Please help me if you have any idea or any possibility to connect the android phone as a GSM Modem to laptop. Here is my mode.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TextmagicRest;
using TextmagicRest.Model;
using System.Net;
using System.Collections.Specialized;
using System.IO;
using System.IO.Ports;
using System.Threading;
namespace SMS_Sending_App_2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
SerialPort sp = new SerialPort();
sp.PortName = textBox3.Text;
sp.Open();
sp.WriteLine("AT" + Environment.NewLine);
Thread.Sleep(100);
sp.WriteLine("AT+CMGF=1" + Environment.NewLine);
Thread.Sleep(100);
sp.WriteLine("AT+CSCS=\"GSM\"" + Environment.NewLine);
Thread.Sleep(100);
sp.WriteLine("AT+CMGS=\"" + textBox1.Text + "\"" + Environment.NewLine);
Thread.Sleep(100);
sp.Write(new byte[] { 26 }, 0, 1);
Thread.Sleep(100);
var response = sp.ReadExisting();
if (response.Contains("ERROR"))
{
MessageBox.Show("SMS failed!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
MessageBox.Show("SMS Sent!!!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
sp.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
}
}
}

Is there a reason for not using a modem? I've seen info that ppl are using their phones but I don't know how they do it. It would be a big risk if the phone offered the modem interface just by connecting to the PC.
For better modem communication look at this project : SMSTerminal

Related

Receiving UDP packets from Wireless IMU application in Unity

I have a project where I have a wireless IMU application on my android phone. Based on the app description, it sends out accel/gyro data in csv format over UDP to a target IP address and port.
Currently I am trying to code a UDPListener in Unity that receives this data.
using UnityEngine;
using UnityEngine.Networking;
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
public class UDPReceiver1 : MonoBehaviour
{
Thread udpListeningThread;
public int portNumberReceive;
UdpClient receivingUdpClient;
string[] delimiters = { ", ", "," };
string[] data;
void Start()
{
initListenerThread();
}
void initListenerThread()
{
Debug.Log("Started on : " + portNumberReceive.ToString());
udpListeningThread = new Thread(new ThreadStart(UdpListener));
// Run in background
udpListeningThread.IsBackground = true;
udpListeningThread.Start();
}
public void UdpListener()
{
receivingUdpClient = new UdpClient(portNumberReceive);
while (true)
{
//Listening
try
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
// Blocks until a message returns on this socket from a remote host.
byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
if (receiveBytes != null)
{
string returnData = Encoding.UTF8.GetString(receiveBytes);
Debug.Log("Message Received" + returnData.ToString());
Debug.Log("Address IP Sender" + RemoteIpEndPoint.Address.ToString());
Debug.Log("Port Number Sender" + RemoteIpEndPoint.Port.ToString());
data = returnData.Split(delimiters, StringSplitOptions.None);
Debug.Log(data);
}
}
catch (Exception e)
{
Debug.Log(e.ToString());
}
}
}
void OnDisable()
{
if (udpListeningThread != null && udpListeningThread.IsAlive)
{
udpListeningThread.Abort();
}
receivingUdpClient.Close();
}
}
As of now this code does not work at all, and I have been very perplexed as to why it isnt working. Many forums seem to follow the same structure and the code seems logical.
When I tested the connection, what i did was to attach this script to a gameobject, set an arbitrary port number, e.g. "12345", and Play. Meanwhile I ran the application on my android phone, with the target IP address being the computer's Ip address and the target port number being the same port number I used earlier.
I would really appreciate it if any kind soul can help, as I have been stuck here for close to 2 weeks;(

How to C# send AT command to GSM modem and get response

I want to get AT command response.
I want to read SMS from my GSM modem.
I fount some code on google, This script send AT commands but not get response.
This is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CSharp_SMS
{
public partial class Form_SMS_Sender : Form
{
private SerialPort _serialPort;
public Form_SMS_Sender()
{
InitializeComponent();
}
private void buttonSend_Click(object sender, EventArgs e)
{
string number = textBoxNumber.Text;
string message = textBoxMessage.Text;
_serialPort = new SerialPort("COM6", 115200);
Thread.Sleep(1000);
_serialPort.Open();
Thread.Sleep(1000);
_serialPort.WriteLine("AT" + "\r");
Thread.Sleep(1000);
string status = _serialPort.ReadLine();
labelStatus.Text = "|-"+ status + "-|";
_serialPort.Close();
}
}
}
This code is not work.
not get response, but send AT commands.
How to get response?
Thanks
if ECHO is off on your modem, you won't get any response to your AT commands.
Ensure echo is enabled by sending ATE1 first
Thread.Sleep(1000);
_serialPort.WriteLine("ATE1" + "\r");
Thread.Sleep(1000);
_serialPort.WriteLine("AT" + "\r");
celu.RtsEnable = true;
celu.DtrEnable = true;
celu.WriteBufferSize = 3000;
celu.BaudRate = 9600;
celu.PortName = "COM26"; // You have check what port your phone is using here, and replace it
celu.Open();
//string cmd = "AT+CLIP=1"; // Here you put your AT command
//celu.WriteLine(cmd);
celu.WriteLine ("AT+CLIP=1"+"\r");
Thread.Sleep(500);
//celu.Open();
string ss = celu.ReadExisting();

C# UDP Chat receive no message

I try to write a UDP-Chat in C#.
I have some unexpected behavoir in my Chat Programm, when I start the programm on two different machines connected to the same Network. At the first mashine the programm works fine it can send and recive messages properly, but on the second machine it can just send messages but it can't recive them.
I testet this with a 3rd mashine too(a VM with a bridged networkinterface), but with the same result, it just can send messages without recieving.
is there a error in my code or is it a desing error?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Net.Sockets;
using System.Net;
using System.Diagnostics;
using System.Threading;
using System.Net.NetworkInformation;
using System.ComponentModel;
using System.Data;
namespace CScharpChat
{
/// <summary>
/// Interaktionslogik für Chat_window.xaml
/// </summary>
public partial class Chat_window : Window
{
string name = "testuser";
UdpClient receiveClient = new UdpClient(1800);
IPEndPoint receiveEndPint = new IPEndPoint(IPAddress.Any, 0);
public Chat_window(string name)
{
this.name = name;
fileWriter("Chat started", false); // write the initial start date in the errorfile
InitializeComponent();
Message_Load(); // starts the listen server theread
}
private void Message_Load()
{
lb_chat.Items.Add(name + " Joined the room...");
Thread rec = new Thread(ReceiveMessageFn);
rec.Start();
}
private void ReceiveMessageFn()
{
try
{
while (true)
{
Byte[] receve = receiveClient.Receive(ref receiveEndPint);
string message = Encoding.UTF8.GetString(receve);
if (message == name + " logged out...")
{
break;
}
else
{
if (message.Contains(name + " says >>"))
{
message = message.Replace(name + " says >>", "Me says >>");
}
ShowMessage(message);
}
}
//Thread.CurrentThread.Abort();
//Application.Current.Shutdown();
}
catch (Exception e)
{
//errorHandler(e);
}
}
private void ShowMessage(string message)
{
if (lb_chat.Dispatcher.CheckAccess())
{
lb_chat.Items.Add(message);// add Item to list-box
lb_chat.ScrollIntoView(lb_chat.Items[lb_chat.Items.Count - 1]);// scroll down to current Item
lb_chat.UpdateLayout();
}
else {
lb_chat.Dispatcher.BeginInvoke(
new Action<string>(ShowMessage), message); // if list-box is not access able get access
return;
}
}
private void tb_eingabe_GotFocus(object sender, RoutedEventArgs e)
{
tb_eingabe.Text = "";
}
private void btn_submit_Click(object sender, RoutedEventArgs e)
{
submit_message();
}
private void tb_eingabe_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
submit_message();
}
}
void submit_message()
{
if (tb_eingabe.Text != "")
{
string data = name + " says >> " + tb_eingabe.Text;
SendMessage(data);
tb_eingabe.Clear(); // clear the textbox-values
tb_eingabe.Focus(); // get focus on tb if the submit button was used, the tb lost the focus
}
}
private void SendMessage(string data)
{
try{
UdpClient sendClient = new UdpClient();
Byte[] message = Encoding.UTF8.GetBytes(data); // use UTF8 for international encoding
IPEndPoint endPoint = new IPEndPoint(IPAddress.Broadcast, 1800); // use a broadcast with the given port
sendClient.Send(message, message.Length, endPoint);
sendClient.Close();
}
catch (Exception e)
{
errorHandler(e);
}
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
string data = name + " logged out...";
SendMessage(data); // send a logout message to the other chat peers
}
// debugging functions
static void errorHandler(Exception errorMsg)
{
MessageBox.Show(errorMsg.ToString()); // create a error-message-box
fileWriter(errorMsg.ToString(), true); // call the file-writer function to write the error in a file
}
static void fileWriter(string fileText, bool append)
{
System.IO.StreamWriter file = new System.IO.StreamWriter(".\\Errorfile.txt", append); // locate the error next to the chat.exe
file.WriteLine(GetTime(DateTime.Now) + "\n " + fileText); // append the date
file.Close();
}
public static String GetTime(DateTime val)
{
return val.ToString("yyyyMMddHHmmssffff"); // return the current date as string
}
}
}
Instead of IPAddress.Broadcast(255.255.255.255) provide your local network broadcast address. See the example below:
IPAddress broadcast = IPAddress.Parse("192.168.1.255"); //replace the address with your local network.
IPEndPoint endPoint = new IPEndPoint(broadcast, 11000);
sendClient.Send(message, message.Length, endPoint);
IPAddress.Broadcast doesn't work in some network.

IRC Bot GUI crash?

Ok so, The bot connects just fine, but when I create the bot, the form crashes. The bot stays connected but also the !about commands doesnt work. If i use this same exact code with a console application everything works fine. The problem is just the UI form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net.Sockets;
namespace cIRCBot
{
public partial class bSetup : Form
{
public bSetup()
{
InitializeComponent();
}
private void createbotbtn_Click(object sender, EventArgs e)
{
string buf, nick, owner, server, chan;
int port;
TcpClient sock = new TcpClient();
TextReader input;
TextWriter output;
//Get nick, owner, server, port, and channel from user
nick = botnick.Text;
owner = botname.Text;
server = servername.Text;
bool isNumber = int.TryParse(portnum.Text, out port);
chan = channelname.Text;
if (isNumber == false)
{
MessageBox.Show("Failed to connect. Make sure the server address and port number are correct.", "Connection Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
//Connect to irc server and get input and output text streams from TcpClient.
sock.Connect(server, port);
if (!sock.Connected)
{
//Console.WriteLine("Failed to connect!");
return;
}
else
{
this.Close();
input = new StreamReader(sock.GetStream());
output = new StreamWriter(sock.GetStream());
//Starting USER and NICK login commands
output.Write(
"USER " + nick + " 0 * :" + owner + "\r\n" +
"NICK " + nick + "\r\n"
);
output.Flush();
//Process each line received from irc server
for (buf = input.ReadLine(); ; buf = input.ReadLine())
{
//Display received irc message
//Console.WriteLine(buf);
//Send pong reply to any ping messages
if (buf.StartsWith("PING ")) { output.Write(buf.Replace("PING", "PONG") + "\r\n"); output.Flush(); }
if (buf[0] != ':') continue;
/* IRC commands come in one of these formats:
* :NICK!USER#HOST COMMAND ARGS ... :DATA\r\n
* :SERVER COMAND ARGS ... :DATA\r\n
*/
//After server sends 001 command, we can set mode to bot and join a channel
if (buf.Split(' ')[1] == "001")
{
output.Write("MODE " + nick + " +B\r\n" + "JOIN " + chan + "\r\n");
output.Flush();
if (buf.Contains("!about"))
{
output.WriteLine("PRIVMSG {0} :" + "I'm a shitty little bot coded by " + botname, channelname);
output.Flush();
}
}
}
}
}
}
}
This is the Main window, I have the other form which you use to setup
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace cIRCBot
{
public partial class mWin : Form
{
public mWin()
{
InitializeComponent();
}
private void newBotToolStripMenuItem_Click(object sender, EventArgs e)
{
bSetup bSetup = new bSetup();
bSetup.Show();
}
private void quitToolStripMenuItem1_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
This is the setup window
I suspect that what causes the problem is the fact that You're doing this.Close() and it gets disposed. After calling Close() You go into for() and try to operate on possibly disposed resources.

Reverse SSH Port Forwarding in C#

I came across this article when trying to put together a reverse SSH solution in visual studio C#:
.NET SSH Port Forwarding
Using his code works up until the point where I actually start the port (port.Start()), then it throws an exception. Doing a reverse tunnel with PuTTY works just fine, so I believe the server is set up correctly. Am I doing something wrong in regards to implementing this SSH.NET library?
using Renci.SshNet;
using Renci.SshNet.Messages;
using Renci.SshNet.Common;
using System;
using System.Net;
using System.Threading;
namespace rSSHTunnelerSSHNET
{
public class Program
{
public static void Main(String[] arg)
{
String Host = "testserver.remote";
String Username = "testuser";
String Password = "password";
using (var client = new SshClient(Host, Username, Password))
{
client.Connect();
if (client.IsConnected)
{
Console.WriteLine("connected");
var port = new ForwardedPortRemote("targetserver.local", 80, "testserver.remote", 8080);
client.AddForwardedPort(port);
port.Exception += delegate(object sender, ExceptionEventArgs e)
{
Console.WriteLine(e.Exception.ToString());
};
port.Start();
}
else
{
Console.WriteLine("failed to connect.");
Console.ReadLine();
}
}
}
}
}

Categories